问题
I have these files: classA.cpp, classA.h, classB.cpp, classB.h, and main.cpp.
All needed libraries are included in both .h files.
In main.cpp I include classA.cpp and classB.cpp.
In classB.cpp I include classB.h and in classA.cpp it is classA.h
I compile it by
g++ main.cpp
(+some unimportant stuff) and it is working perfectly.
But I am almost certainly sure, that on our lectures we were told to do that differently, sadly I can't find it now.
Is this the best way of including and compiling? If not, what is?
回答1:
the simply way:g++ main.cpp ClassA.cpp ClassB.cpp etc.cpp
more advanced way you should use a makefile.
enter link description here
回答2:
Normally you don't include source files into other source files. In fact, the reason we have header files is so that we can use the same declarations in all files, whilst compiling definitions only once.
So your main.cpp should include classA.h and classB.h instead of classA.cpp and classB.cpp:
#include "classA.h"
#include "classB.h"
#include <algorithm> // and whatever else you need
int main()
{
// your code....
}
Then write a simple Makefile:
CXXFLAGS += -Wall -Wextra
main: main.o classA.o classB.o
$(LINK.cpp) $(OUTPUT_OPTION) $^
main.o: main.cpp
main.o: classA.h
main.o: classB.h
classA.o: classA.cpp classA.h
classB.o: classB.cpp classB.h
For bigger projects, you can write a rule to create the dependencies from the source files automatically, but we can start as above by hand-generating them.
Now, the correct commands will be run when you execute
make
来源:https://stackoverflow.com/questions/43849333/how-to-include-and-compile-multiple-c-files