Inline function in header file in C

I tried to find a good answer online, but could not get it, I completely understood. Suppose I have the header "add.h":

inline int add(int a, int b){ return a+b; } 

File named "adddouble.c":

 #include "add.h" int adddouble(int a, int b){ return 2*add(a,b); } 

File named "addedquare.c":

 #include "add.h" int addsquare(int a, int b){ return add(a,b)*add(a,b); } 

Main file "main.c":

 #include<stdio.h> int adddouble(int, int); int addsquare(int, int); int main(){ printf("add double = %d\n", adddouble(10,20)); printf("add square = %d\n", addsquare(10,20)); return 0; } 

I use gcc5.2.0 to compile these files, but got: "Undefined characters for x86_64 architecture:". If I add static to the built-in function in add.h or add the declaration "extern int add (int, int);" to "adddouble.c", it compiles successfully without errors. I am new to the built-in function, I do not know how to explain and understand this behavior. thanks

+5
source share
1 answer

According to http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf , it looks like built-in functions behave differently in C and C ++:

Any function with internal communication can be a built-in function. For external communications, the following restrictions apply: if a function is declared using the built-in function specifier, then it must also be defined in the same translation unit. If the entire volume of the declaration file for a function in a translation unit includes a built-in function specifier without extern, then the definition in this translation unit is a built-in definition. The built-in definition does not provide an external definition of a function, and does not prohibit an external definition in another translation unit. The built-in definition is an alternative to the external definition, which the translator can use to implement any function call in the same translation. It is not indicated whether the function call uses a built-in definition or an external definition. 140)

If you do not put static there, you define an inline function with external communication without creating an external definition.

extern int add(int, int); sets an external definition for this function, and you need to do it exactly once (no matter in which file) for successful binding (or you can mark the built-in static function and the problem is zero).

(In C ++, inline creates weak external definitions in each translation unit, so you don’t have to worry about labeling things static or creating just one external definition for an inline function - g ++ should just compile it with for f in *.c; do g++ -c "$f"; done; g++ *.o no problem.)

+6
source

Source: https://habr.com/ru/post/1237594/


All Articles