user485498
user485498

Reputation:

C Compilation With missing function definitions

I've been following a couple of C tutorials and there is a certain point I'm not sure I understand. Some examples show function prototypes but without function definitions. The tutorials say that the code should compile ok, even if they won't run.

Is this correct? Should C programs with missing function definitions compile ok?

Upvotes: 1

Views: 1050

Answers (4)

Gowtham
Gowtham

Reputation: 1475

Yes, there is something called linking. This is a process of resolving references to different symbols, like variables, functions etc. The compiler is happy even if it does not know anything about a function's definition. However, if compiler knows about the function's prototype, it can check if the function is used correctly, so that mistakes get flagged early.

Refer Wikipedia or google to know more about linking.

Upvotes: 0

Adam Mihalcin
Adam Mihalcin

Reputation: 14458

There's a big difference between function declarations and function definitions. To use a function, you have to declare the function first, but you can only compile the program if the functions you use have been defined.

The C compilation process is a series of steps that feed one into another. In a typical compilation process, first the preprocessor runs, then the compiler generates assembly language for each source file, then the assembler turns that assembly language into machine code, and then the linker puts all the necessary pieces together. The compiler step typically won't finish unless you declare functions, but the compiler doesn't care about where the functions are actually implemented - it just generates assembly language code with holes where calls to the real functions can be placed. The linker fills in those holes with calls to the actual functions.

So you can declare a function but define it in a different file, which is what the tutorial was probably doing. However, you still have to define the function somewhere, or else you won't get a full executable binary.

Upvotes: 0

hmjd
hmjd

Reputation: 121971

The source code will compile with declarations only, but if any of the functions are called then a linker error will occur if the functions are not defined somewhere.

Upvotes: 4

zvrba
zvrba

Reputation: 24546

Yes, this is correct. It is the feature that makes it possible to split a big program into multiple source files.

Upvotes: 2

Related Questions