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

前端 未结 11 928
耶瑟儿~
耶瑟儿~ 2020-11-22 09:43

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

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 10:30

    Now that I've separated 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 the 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.

提交回复
热议问题