Reputation:
I have read multiple search results about this including this link, but I still don't get it: https://gcc.gnu.org/gcc-5/porting_to.html
Why does this simple code generate a linker error:
#include <stdio.h>
inline int add(int a , int b){
return a+b;
}
int main(){
printf("%d\n", add(1,2));
return 0;
}
All I want for the compiler to inline add
. There are no other translation units, this is the only one. Why does it give me a Undefined symbol
linker error?
While we are at it, I keep reading there is a difference between inline add()
and extern inline add()
. I thought all functions in C
are extern
by default?
error messgae:
$clang 0.c
Undefined symbols for architecture x86_64:
"_add", referenced from:
_main in 0-1cc8ba.o
Upvotes: 1
Views: 601
Reputation: 310960
From the C Standard (6.7.4 Function specifiers)
- ...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. An inline definition provides an alternative to an external definition, which a translator may use to implement any call to the function in the same translation unit. It is unspecified whether a call to the function uses the inline definition or the external definition.
So it seems that the linker does not see the external definition of the inline function in your program.
To avoid the error use the storage specifier either static
or extern
.
For example
extern inline int add(int a , int b){
return a+b;
}
or
static inline int add(int a , int b){
return a+b;
}
Upvotes: 2