Using G++ to compile multiple .cpp and .h files

2019-01-01 05:09发布

I've just inherited some C++ code which was written poorly with one cpp file which contained the main and a bunch of other functions. There are also .h files which contain classes and their function definitions.

Until now the program was compiled using the command g++ main.cpp. Now that I've seperated the classes to .h and .cpp files do I need to use a makefile or can I still use the g++ main.cpp command?

9条回答
与风俱净
2楼-- · 2019-01-01 05:45

Now that I've seperated the classes to .h and .cpp files do I need to use a makefile or can I still use the "g++ main.cpp" command?

Compiling several files at once is a poor choice if you are going to put that into the Makefile.

Normally in a Makefile (for GNU/Make) it should suffice to write that:

# "all" is name of the default target, running "make" without params would use it
all: executable1

# for C++, replace CC (c compiler) with CXX (c++ compiler) which is used as default linker
CC=$(CXX)

# tell which files should be used, .cpp -> .o make would do automatically
executable1: file1.o file2.o

That way make would be properly recompiling only what needs to be recompiled. One can also add few tweaks to generate the header file dependencies - so that make would also properly rebuild what's need to be rebuilt due to the header file changes.

查看更多
看风景的人
3楼-- · 2019-01-01 05:46

.h files will nothing to do with compiling ... you only care about cpp files... so type g++ filename1.cpp filename2.cpp main.cpp -o myprogram

means you are compiling each cpp files and then linked them together into myprgram.

then run your program ./myprogram

查看更多
荒废的爱情
4楼-- · 2019-01-01 05:46

~/In_ProjectDirectory $ g++ coordin_main.cpp coordin_func.cpp coordin.h

~/In_ProjectDirectory $ ./a.out

... Worked!!

Using Linux Mint with Geany IDE

When I saved each file to the same directory, one file was not saved correctly within the directory; the coordin.h file. So, rechecked and it was saved there as coordin.h, and not incorrectly as -> coordin.h.gch. The little stuff. Arg!!

查看更多
登录 后发表回答