0

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.

Lucifer
  • 29,392
  • 25
  • 90
  • 143
  • 2
    Remove the header from the compile line, you don't need to compile headers. – user657267 Mar 13 '15 at 06:10
  • BTW, a program can (and usually do) have errors even if it is compiled without diagnostics from the compilers. These errors are called *bugs* and you might spend weeks to find and correct one! – Basile Starynkevitch Mar 13 '15 at 06:40

1 Answers1

1

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 (e.g. with time) don't forget to ask the compiler to optimize!

PS. Your g++ commands might need more arguments, e.g. -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++

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547