3

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?

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

2 Comments

Voted up for clarity, but for anything more complex I would investigate makefiles
i agree with @ Brian Agnew . Its true .. When I will use make files . But for the small compiling . just using command is fine ...
7

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

1 Comment

By the way see my previous question here to see the differences between g++ and gcc: stackoverflow.com/questions/172587/…
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

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.