2

I am an Ubuntu user. What is the difference between g++ file.cpp -o file and g++ -c file.cpp?

I know that g++ -c file.cpp creates an object file, file.o.

But what about g++ file.cpp -o file?

I have been using this command for a long time, but I don't know the file generated as an output (it is just "file"). I have to run ./file to execute the file.

12
  • 1
    While it could be a little overwhelming, the GCC manual is the best place to find the answers to questions about its command-line options. Commented Jul 25, 2021 at 13:08
  • 3
    The -c and -o options are covered in "Options Controlling the Kind of Output". Commented Jul 25, 2021 at 13:17
  • What is the meaning of "Compile or assemble the source files, but do not link. The linking stage simply is not done". Thanks for the help @G.M. Commented Jul 25, 2021 at 13:22
  • @Pratyparty Re. compiling and linking, you'll get some useful info from this post. Commented Jul 25, 2021 at 13:32
  • The "natural" way to build a source file is to generate an executable program file. There are options to either stop at intermediate steps or to generate different kinds of output. For example you could ask GCC to stop after preprocessing with the -E option; Or to stop and generate only assembly output with the -S option; Or to stop after creating an object file with the -c option. Commented Jul 25, 2021 at 13:34

3 Answers 3

5

With -o you can specify the output file name. In your, e.g., g++ file.cpp -o file means: compile file.cpp to file.

Without -o your source code will compile to a.out file.

If you worry about others option in g++, you can always use g++ --help. It will show you all parameters and their meanings. For example, -o meaning from help:

-o <file> : Place the output into <file>

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

Comments

3

g++ file.cpp -o file produces an executable file (which normally have no extensions on Linux). -o specifies the output file name. If you do just g++ file.cpp, the file will be named a.out.

It's equivalent to g++ -c file.cpp followed by g++ file.o -o file, except that the file.o is not saved anywhere.

Note that you can use -o <filename> with -c as well, to change the name of the object file.

Comments

0

-o simply means "output" and allows you to choose your output file's name. It remains totally allowed to specify both -c and -o if you need it.

Simply, cc used to name a final, linked executable a.out for historical reasons and will still keep on doing it for while, when using -c is primarily meant to compile multiple parts before assembling from the beginning, thus preserving the original name.

That's why see more often -o specified when compiling final executable than other types of compiled files.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.