irasin
irasin

Reputation: 165

compile undefined and unused function in c++

Here is the sample code. I have a function print without definition and I used it in the print_in_A() in the struct A.

Why can this code compile and run?

void print(int x);


struct A {
    void print_in_A() {
        print(1);
    }
};

int main()
{
    A a;
    return 0;
}

And also, if I define an inline function like this, it can compile and run too. But if I remove the inline keyword, it fails to compile.

void print(int x);

inline void print_int(int a) {
    print(a);
}


int main()
{
    return 0;
}

DEMO - Without error when inline is used

DEMO - With error when inline is not used

Can anyone tell me why?

Upvotes: 2

Views: 515

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117643

If the compiler can be sure that the functions using print are never used, it can remove them. In those cases, the linker will not complain since there will be no unresolved symbols. The non-inline print_int can't be removed since it may be used from another translation unit, hence, you get a linking error.

Upvotes: 2

Related Questions