0

My project has this folder structure:

Project/
--Classes/
----Class1.h
----Class1.cpp
--main.cpp

"Class1.h" contains method definitions, "Class1.cpp" is the source code for "Class1.h".

The source code of "Class1.h" is like this:

class Class1 {
  public:
    void do_something();
};

The source code of "Class1.cpp" is like this:

#include "Class1.h"

void Class1::do_something() {
  //
} 

The source code of "main.cpp" is like this:

#include "Classes/Class1.h"

int main(int argc,char** args) {
  Class1* var = new Class1();
  var->do_something();
  return 0;
}     

However, when compiling "main.cpp", the compiler doesn't know where the implementation of methods in Class1 is, so it shows linking error about undefined reference.

Do I have to add any path into the command line so the compiler knows what source files it has to compile? How to tell the compiler that it must compile "Class1.cpp" also?

jondinham
  • 8,271
  • 17
  • 80
  • 137

3 Answers3

5

You need to feed all files in your project to the compiler, not just "main.cpp". Here you can read about the basics of compiling multiply files together with Gcc.

Another option would be to compile your classes as a dynamic or static library, but you should start with simply compiling them together if you're not quite familiar with libraries.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
2

The correct way to do it is doing the header inclusion in the Class1.cpp file. That way if the Class1.cpp is compiled as a library, you can use the header file to get the declarations.

The other way around, if you will directly use the Class1.cpp, compiling it with your project. You should include Class1.cpp in your main.cpp.

Etherealone
  • 3,488
  • 2
  • 37
  • 56
2

You need to know about building (compiling and linking) C++ applications. This topic usually don't describe in programming books about C++ and only way to do it - google and programming community sites with articles.

Fast answer is:

g++ -c Classes/Class1.cpp -o Class1.o
g++ -c main.cpp -o main.o
g++ Class1.0 main.0 -o ProjectName

It's a simple set of commands to compiling and linking program. Usually it would be done by build system (make, qmake, cmake, waf, scons, ant etc). Also, IDE can build program without additional configuration, Visual Studio for example.

Torsten
  • 21,726
  • 5
  • 24
  • 31