tags:

views:

483

answers:

6

Hi, 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

Thanks.

+3  A: 

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.

EFraim
+2  A: 

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.

e.James
+9  A: 

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.

anon
+2  A: 

-c flag means Compile Only

Try g++ -o test test.cpp

Salgar
+1  A: 

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.

cube
A: 

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.