Question

I've found static inline function in Bionic libc (stdlib.h).

I want to compile a file without including stdlib.h.

As example: test file:

extern int test(void)
void foo() {
    int a = test();
}

int main() {
    foo ();
    return 0;
}

Why do I need to include header file for using functions which defined as static inline?

Was it helpful?

Solution

From Using the GNU compiler:

When a function is both inline and static, if all calls to the function are integrated into the caller, and the function's address is never used, then the function's own assembler code is never referenced. In this case, GCC does not actually output assembler code for the function, unless you specify the option -fkeep-inline-functions. Some calls cannot be integrated for various reasons (in particular, calls that precede the function's definition cannot be integrated, and neither can recursive calls within the definition). If there is a nonintegrated call, then the function is compiled to assembler code as usual. The function must also be compiled as usual if the program refers to its address, because that can't be inlined.

Thus if yout don't include stdlib.h, there is no code the linker could use to link against the symbol test(), because in fact there is no such function. But although your program will compile and run if test() is not inline you should always include the appropriate header files, as this allows the compiler to check for return value and paraemeter types.

OTHER TIPS

extern int test(void);
void foo() {
    int a = test();
}

int main() {
    foo ();
    return 0;
}

extern is an external variable is a variable defined outside any function block. so, complier will find this function. if you not including this file, the complier can't find it.

Although this question has an accepted answer, I would like to put some more insights into the problem and clear some more doubts :-

According to c99 standard (§6.2.2 #3)

If the declaration of a file scope identifier for an object or a function contains the storage class specifier static, the identifier has internal linkage.

A function with internal linkage is only visible inside one translation unit. The linker never hears about those functions with internal linkage, so it knows nothing about them. In short the functions or variables with internal linkages are invisible to the linker. By now , you must have understood why we must include the header files.

Don't forget to check the c standard documentation .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top