4

I'm 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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
n00ki3
  • 14,529
  • 18
  • 56
  • 65

4 Answers4

22

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
  • 34,529
  • 29
  • 100
  • 137
  • 8
    Voted up for clarity, but for anything more complex I would investigate makefiles – Brian Agnew Jul 20 '09 at 11:52
  • i agree with @ Brian Agnew . Its true .. When I will use make files . But for the small compiling . just using command is fine ... – joe Jul 20 '09 at 11:53
8

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
  • 339,232
  • 124
  • 596
  • 636
  • 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 Jul 20 '09 at 11:55
3

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

2

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
  • 775
  • 4
  • 13
  • 3
    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 Jul 20 '09 at 12:49