ponypaver
ponypaver

Reputation: 397

C++ inline resulted in undefined reference

t.h

#ifndef __T_H__
#define __T_H__

class A
{
    int j;
public:
    A(int i); 
};

#endif

t.cpp

#include "t.h"

inline A::A(int i):j(i){}

main.cpp

#include "t.h"

int main(void)
{
    A a(2);

    return 0;
}

compile:

$ g++ t.cpp main.cpp -o main
/tmp/ccRjri7I.o: In function `main':
main.cpp:(.text+0x15): undefined reference to `A::A(int)'
collect2: error: ld returned 1 exit status

If I remove the inline from the implementation, it'ok. don't know why is this happen.

Upvotes: 3

Views: 2255

Answers (1)

John Zwinck
John Zwinck

Reputation: 249592

Inlines must be defined in the same translation unit where they are used. By defining your "inline" function in the .cpp file, it is only usable in the same .cpp file. You need to move it either to the header file, or some special "inlines" file that some projects prefer to keep their implementation details a bit more hidden (you'd then #include that inlines file, either in your header or in main.cpp).

Upvotes: 5

Related Questions