Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including source files in C

So I get the point of headers vs source files. What I don't get is how the compiler knows to compile all the source files. Example:

example.h

#ifndef EXAMPLE_H
#define EXAMPLE_H

int example(int argument); // prototype

#endif

example.c

#include "example.h"

int example(int argument)
    {
    return argument + 1; // implementation
    }

main.c

#include "example.h"

main()
    {
    int whatever;
    whatever = example(whatever); // usage in program
    }

How does the compiler, compiling main.c, know the implementation of example() when nothing includes example.c?

Is this some kind of an IDE thing, where you add files to projects and stuff? Is there any way to do it "manually" as I prefer a plain text editor to quirky IDEs?

like image 849
Core Xii Avatar asked Sep 14 '09 14:09

Core Xii


1 Answers

Compiling in C or C++ is actually split up into 2 separate phases.

  • compiling
  • linking

The compiler doesn't know about the implementation of example(). It just knows that there's something called example() that will be defined at some point. So it just generated code with placeholders for example()

The linker then comes along and resolves these placeholders.

To compile your code using gcc you'd do the following

gcc -c example.c -o example.o
gcc -c main.c -o main.o
gcc example.o main.o -o myProgram

The first 2 invocations of gcc are the compilation steps. The third invocation is the linker step.

like image 119
Glen Avatar answered Nov 12 '22 04:11

Glen