-1

I have 3 files: main.cpp, gp_frame.cpp and gp_frame.h. I wish to declare a class (named gp_frame) in gp_frame.h and define the member functions in gp_frame.cpp and want to use the class in main.cpp.

Broadly, the three files:

/*main.cpp*/
#include "gp_frame.h"

void plotpicture(unsigned int a, unsigned int b, unsigned int c, unsigned int d, unsigned int e){
 anita.wait_enter("Some string\n");
}

int main(){
 gp_frame anita(true);
 plotpicture(1,2,3,4);
 return 0;
}

/*gp_frame.h*/

class gp_frame{
 public: void wait_enter(std::string uzi);
 gp_frame();
 gp_frame(bool isPersist);
};

/*gp_frame.cpp*/
#include "gp_frame.h"

void gp_frame::wait_enter(std::string uzi){
 /*Some of code*/
}
gp_frame::gp_frame(){
 /*Some of code*/
}
gp_frame::gp_frame(bool isPersist){
 /*Some of code*/
}

Then, I want to compile and link the files:

g++ -c main.cpp -w -Wall
g++ -c gp_frame.cpp -w -Wall
g++ gp_frame.o main.o -o Myprogram

And everything is OK. However, if I want to declare/define function wait_enter as inline like:

/*in gp_frame.h*/
public: inline void wait_enter(std::string uzi);
/*in gp_frame.cpp*/
inline void gp_frame::wait_enter(std::string uzi){
 /*Some of code*/
}

the compiler works as well, but the linker throws me an error:

main.o: In function `plotpicture(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int)':
main.cpp:(.text+0x2c6b): undefined reference to `gp_frame::wait_enter(std::string)'
collect2: error: ld returned 1 exit status

Can you explain me how to solve the problem or what do I wrong?


Sadly, neither extern inline nor static inline solves my problem.

Tom Solid
  • 2,226
  • 1
  • 13
  • 32
  • Inline functions must be defined in the header. It does not make sense to have an inline function that is defined only in the implementation. How can the compiler see the definition to inline it? – Cody Gray - on strike Jul 08 '16 at 13:47
  • Possible duplicate of [undefined reference when calling inline function](http://stackoverflow.com/questions/19068705/undefined-reference-when-calling-inline-function) – Jossie Calderon Jul 08 '16 at 15:55

1 Answers1

3

what do I wrong?

You declare an inline function gp_frame::wait_enter(std::string), but you didn't define the function in all of the compilation units (source files) that use the function which is required by the standard.

In particular, you only defined the function in gp_frame.cpp but not in main.cpp, even though you do use the function in main.cpp.

how to solve the problem

Define inline functions in all compilation units that use them. The idiomatic way to do that is to define them in the same header that also declares them (gp_frame.h in this case).

eerorika
  • 232,697
  • 12
  • 197
  • 326