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:22

I know this question has been asked years ago but still wanted to share how I usually compile multiple c++ files.

  1. Let's say you have 5 cpp files, all you have to do is use the * instead of typing each cpp files name E.g g++ -c *.cpp -o myprogram.
  2. This will generate "myprogram"
  3. run the program ./myprogram

that's all!!

The reason I'm using * is that what if you have 30 cpp files would you type all of them? or just use the * sign and save time :)

p.s Use this method only if you don't care about makefile.

查看更多
何处买醉
3楼-- · 2019-01-01 05:24

list all the other cpp files after main.cpp.

ie

g++ main.cpp other.cpp etc.cpp

and so on.

Or you can compile them all individually. You then link all the resulting ".o" files together.

查看更多
旧时光的记忆
4楼-- · 2019-01-01 05:33

You can use several g++ commands and then link, but the easiest is to use a traditional Makefile or some other build system: like Scons (which are often easier to set up than Makefiles).

查看更多
查无此人
5楼-- · 2019-01-01 05:34

To compile separately without linking you need to add -c option:

    g++ -c myclass.cpp
    g++ -c main.cpp
    g++ myclass.o main.o
    ./a.out
查看更多
君临天下
6楼-- · 2019-01-01 05:36

I used to use a custom Makefile that compiled all the files in current directory, but I had to copy it in every directory I needed it, everytime.

So I created my own tool - Universal Compiler which made the process much easier when compile many files.

查看更多
梦寄多情
7楼-- · 2019-01-01 05:37

You can still use g++ directly if you want:

g++ f1.cpp f2.cpp main.cpp

where f1.cpp and f2.cpp are the files with the functions in them. For details of how to use make to do the build, see the excellent GNU make documentation.

查看更多
登录 后发表回答