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

前端 未结 11 827
耶瑟儿~
耶瑟儿~ 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:25

    If you want to use #include <myheader.hpp> inside your cpp files you can use:

    g++ *.cpp -I. -o out
    
    0 讨论(0)
  • 2020-11-22 10:28

    .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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 10:31

    ~/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!!

    0 讨论(0)
  • 2020-11-22 10:33

    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.

    0 讨论(0)
提交回复
热议问题