How to include and compile multiple C++ files? [closed]

旧城冷巷雨未停 提交于 2019-12-13 09:22:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!