简体   繁体   中英

How to compile and run a program that uses multiple files through terminal?

So I'm trying to practice and learn how to use a text editor and the command line interface (terminal on mac) but i'm having trouble getting it to compile. I'm writing in c++ and i've separated my main file, class and class definitions into multiple files. I want to compile and run the program using terminal but am having issues. I use

 g++ file1.cpp file2.cpp file3.h -o run 

to compile and I get the error message "cannot specify -o when generating multiple output files."

I'm planning on having even more files in this program and don't know if this is even the best way to compile each time? Regardless, how do I compile this program so that I can run? I know the program doesn't have any errors because I tested it in the IDE Xcode.

If you really want, you could type several commands ( -std=c++11 tells the compiler that it is C++11 code, -Wall asks for almost all warnings, -Wextra asks for more of them, -g asks for debug information, and -c avoids a linking step)

 g++ -std=c++11 -Wall -Wextra -g -c file1.cpp
 g++ -std=c++11 -Wall -Wextra -g -c file2.cpp
 g++ -std=c++11 -Wall -Wextra -g -c file3.cpp

These commands are generating object files file1.o , file2.o , file3.o which you can link to make an executable:

 g++ -std=c++11 -g file1.o file2.o file3.o -o run

BTW, you could have run all in a single command:

 g++ -std=c++11 -Wall -Wextra -g file1.cpp file2.cpp file3.cpp -o run

but this is not optimal (since usually you edit one file at once, and the other files might not need to be recompiled).

But you really want to use GNU make , by writing your Makefile (see this example ) and simply compiling with make ; if you change only file2.cpp then make would notice that only file2.o has to be regenerated (and the final link to make again run )

You don't need to compile header files (they are preprocessed by the g++ compiler). You might be interested in precompiled headers and makefile dependencies generation .

Once your program is debugged (with the help of a debugger like gdb and also of valgrind ....) you could ask the compiler to do optimizations by replacing -g with -O or -O2 (you could even compile with both -g -O ). If you benchmark your program (eg with time ) don't forget to ask the compiler to optimize!

PS. Your g++ commands might need more arguments , eg -I ... to add an include directory, -DNAME to define a preprocessor name, -L ... to add a library directory, -l ... to link a library, and order of arguments is important for g++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM