Home > Blockchain >  C: Linking functions works without sharing headers or extern declaration
C: Linking functions works without sharing headers or extern declaration

Time:08-16

I am currently "playing" around in a quite big and old codebase and, quite unfortunately, it has no fixed style attached to it. So it was just made to work but that also means that quite a lot of it can be described as spaghetti code.

I came across something that I do not fully undersand. Compiler is from ARM/KEIL and it is for an embedded system.

first file:

fileA.c
// prototype
int GetSomething( int a );

// implementation
int GetSomething( int a) {
    DoSomething();
}

second file:

fileB.c
// prototype
int GetSomething( int a )

void main ( void ) {
    GetSomething(10);
}

There are no headers which have a declaration for the function GetSomething but the function is still correctly linked. Originally, there are a extern keyword in the second file in the declaration of GetSomething, but with or without that results in the same binary. The code has been tests and works.

I've seen Stackoverflow Question but that doesn't seem to cover my case as it seems to have nothing to do with the extern keyword.

I hope that somebody can explain that to me or tell me what is going on. Thanks.

CodePudding user response:

Using header files and #include directives are just a more organized and neater way to use various parts of code in a program at different places.

When you do something like #include "header.h" a copy of header.h is put into the file.

So when you write

GetSomething( int a );

you are essentially doing an alternative to what #include would normally do.

Another important detail is that function prototypes have the extern storage class specifier by default.

One thing you should keep in mind is that declaring function prototypes across your files manually can result in error prone and hard to maintain code. So it is best to utilize header files and #include directives.

  • Related