What is "object" in "object file" and why is it called this way?

sthlm58 picture sthlm58 · Nov 23, 2011 · Viewed 11.6k times · Source

I was asked a question: "What is an 'object file'?".

After looking at Wiki, I only know that it contains objects.

But what are those objects and why someone called them that way?

Answer

Macmade picture Macmade · Nov 23, 2011

Object files (or object code) are machine code files generated by a compiler from source code.

The difference with an executable is that the object file isn't linked, so references to functions, symbols, etc aren't defined yet (their memory addresses is basically left blank).

When you compile a C file with GCC:

gcc -Wall -o test test.c

Here you are compiling AND linking. So you'll got an executable, containing all the memory addresses references for the symbols it contains (libraries, headers, etc).

But when you do this:

gcc -Wall -o test.o -c test.c

You'll produce and object file. It's also machine code, but it will need to be linked in order to produce an executable, or a library.

When you have a project with many C files (for instance), you'll compile each one into object code, and then you will link all object files together in order to produce the final product.

For instance:

gcc -Wall -o foo.o -c foo.c              // Object file for foo.c
gcc -Wall -o bar.o -c bar.c              // Object file for bar.c
gcc -Wall -o main.o -c main.c            // Object file for main.c
gcc -Wall -o software foo.o bar.o main.o // Executable (foo + bar + main)

The term object stands here for sequences of unlinked machine code (basically). An object file contains objects.

You asked: why is this call that way. I can't really answer. Why is "blue" named "blue"? ; )

It's just the term used since... well, decades...

For information, the GCC Internals documentation only defines object code as:

The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.

Pretty vague about the historical reason...

I simply hope you now understand better what is an object file. I think it's more important than knowing why it's called like that, as words are just, well, words...