Some Name
Some Name

Reputation: 9521

External definition and inline definition

gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0


I'm experimenting with inline and external definitions and here are 2 source files linked together:

foo.c:

#include <stdio.h>

void foo(void){
    printf("Test external definition\n");
}

main.c:

#include <stdio.h>

inline void foo(void){
    printf("Test\n");
}

int main(void){
    foo();
}

Compiling an linking 2 files together Test is printed in console.

N2346::6.7.4/p6 provides that:

It is unspecified whether a call to the function uses the inline definition or the external definition.

and

If all of the file scope declarations for a function in a translation unit include the inline function specifier without extern , then the definition in that translation unit is an inline definition. An inline definition does not provide an external definition for the function, and does not forbid an external definition in another translation unit.

So in the example there are inline definition and external definition. And it's unspecified which one is called.

I ran tests and in my case the inline definition was called. Is there a way to force gcc to call external definition? Maybe there is some flag?

Upvotes: 0

Views: 162

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

Citing from 6.7.4/10:

A file scope declaration with extern creates an external definition.

For the external definition to be available to choose from (however the compiler chooses) there must actually be an extern function declaration.

From the example:

inline double fahr(double t) { ... }

...

extern double fahr(double); // creates an external definition

Upvotes: 1

Related Questions