4

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

0

6 Answers 6

12

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

3

-c flag means Compile Only

Try g++ -o test test.cpp

Comments

2

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.

Comments

1

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.

Comments

1

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.

Comments

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.