views:

523

answers:

4

hi im new to c++ and i want to compile my testprogram .
i have now 3 files "main.cpp" "parse.cpp" "parse.h"

how can i compile it with one command ?

+6  A: 

Typically you will use the make utility with a makefile. Here is a tutorial.

If you only want a simple compilation though you can just use gcc directly...

You don't specify the .h files as they are included by the .cpp files.

gcc a.cpp b.cpp -o program.out
./program.out

Brian R. Bondy
By the way see my previous question here to see the differences between g++ and gcc: http://stackoverflow.com/questions/172587/what-is-the-difference-between-g-and-gcc
Brian R. Bondy
+20  A: 

Compile them both at the same time and place result in a.out

$ g++ file.cpp other.cpp

Compile them both at the same time and place results in prog2

$ g++ file.cpp other.cpp -o prog2

Compile each separately and then link them into a.out

$ g++ -c file.cpp
$ g++ -c other.cpp
$ g++ file.o other.o

Compile each separately and then link them into prog2

$ g++ -c file.cpp
$ g++ -c other.cpp
$ g++ file.o other.o -o prog2
joe
Voted up for clarity, but for anything more complex I would investigate makefiles
Brian Agnew
i agree with @ Brian Agnew . Its true .. When I will use make files . But for the small compiling . just using command is fine ...
joe
nicely explained
Brian R. Bondy
A: 

In most cases, if you use g++ compiler, you have to compile the main, using this command :

g++ main.cpp -o main

The result executable will be "main" in this case. The option "-o" means that the compiler will optimize the compilation. If you want to know more about theses options, look at the man pages (man g++).

Timothée Martin
The -o option sets the name of the output binary.-On is for optimisation where n is a number from 0 to 4 or s depending on the optimisations required.
John Barrett
+2  A: 

Using command line compilation is trivial for a simple basic program but it gets more difficult nor impossible when you'll try to compile a "real program". I mean not a big one a simple collection of various source files, libraries with some compiler options for example.

For this purposes there are various build systems and the one I recommend you is CMake. It's an open source cross-platform build system very powerful and ease to use. I use it every day and I think it's more easy to use than other ones like the AutoTools

More information on: www.cmake.org

msantamaria