seg.server.fault
seg.server.fault

Reputation: 20008

C++ programs, compiling with g++

I am very aware of compiling C++ programs with g++ in linux environment. But, may be I am missing something, I am getting this strange output/behaviour.

I have source file in test.cpp. To compile this, I did

(1)
g++ -c test.cpp 
g++ -o test test.o
./test

Everything works fine. But when I did compling and linking in same stage, like this

(2)
g++ test.cpp -o test 
./test => Works fine
(3)
g++ -c test.cpp -o test => Doesn't work

In my last case, test is generated but is no more executable; but in my guess it should work fine. So, what is wrong or do I need to change some settings/configuration?

I am using g++ 4.3.3

Upvotes: 4

Views: 10879

Answers (6)

Alexandre
Alexandre

Reputation:

Read man g++. The switch -c is to compile only but not to link. g++ -c test.cpp -o test does what g++ -c test.cpp does but the object file will be test istead of the default name test.o. An object file cannot be executed.

Upvotes: 1

cube
cube

Reputation: 3938

from the gcc manual:

  -c  Compile or assemble the source files, but do not link.  The linking
      stage simply is not done.  The ultimate output is in the form of an
      object file for each source file.

You must link the compiled object files to get the executable file. More info about compiling and linking and stuff is here.

Upvotes: 1

Salgar
Salgar

Reputation: 7775

-c flag means Compile Only

Try g++ -o test test.cpp

Upvotes: 3

anon
anon

Reputation:

When you say:

g++ -c test.cpp -o test

The -c flag inhibits linking, so no executable is produced - you are renaming the .o file.

Basically, don't do that.

Upvotes: 12

James Eichele
James Eichele

Reputation: 119106

Specifying -o in the g++ command line tells the compiler what name to give the output file. When you tried to do it all in one line, you just told the compiler to compile test.cpp as an object file named test, and no linking was done.

Have a look at the fabulous online manual for GCC for more details.

Upvotes: 2

EFraim
EFraim

Reputation: 13028

You are forcing compiler to produce an object file and name it like an executable.

Essentially your last line tells: compile this to an object file, but name it test, instead of test.obj.

Upvotes: 3

Related Questions