Abraham Abraham - 1 month ago 10
C++ Question

How to use .cpp and .h files inside subdirectories?

This is the contents of a directory in my system:

/directory/
classes/
class1.cpp
class1.h
main.cpp


And here is the contents of above files:

main.cpp

#include "classes/class1.h"

int main(){
class1 test;
return 0;
}


class1.h

class class1 {
public:
class1();
void test();
};


class1.cpp

#include "class1.h"

class1::class1(){
}
class1::test(){
}


The question is why I can't compile
main.cpp
?

ghasemi@ghasemi-MS-7693:~/Desktop/directory$ g++ *.cpp
/tmp/ccEvIogL.o: In function `main':
main.cpp:(.text+0x1f): undefined reference to `class1::class1()'
collect2: error: ld returned 1 exit status

Answer

In your main directory there is only one .cpp file, and the * wildcard doesn't look in sub-directories. You need to explicitly name all the source files, or use multiple wildcards (not something I recommend).

So something like

g++ main.cpp classes/class1.cpp