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

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

    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.

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

    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
    
    0 讨论(0)
  • 2020-11-22 10:12

    As rebenvp said I used:

    g++ *.cpp -o output
    

    And then do this for output:

    ./output
    

    But a better solution is to use make file. Read here to know more about make files.

    Also make sure that you have added the required .h files in the .cpp files.

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

    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).

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

    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.

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

    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.

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