Linker error inline function

杀马特。学长 韩版系。学妹 提交于 2019-12-07 01:34:07

问题


I got some compiler/linker errors and i don't know what is the correct method to proceed. I'm in this situation:

  • a.h: in this file is defined a function declared as "inline", for example: inline void foo1();
  • b.h: in this file is defined a function declared as "inline" that calls foo1(): inline void foo2();
  • main.c: there are some functions calls of both foo1 and foo2().

Now, if i declare foo1 and foo2 in a.h and b.h as extern inline void i got the following error:

prj/src/b.o: In function foo1': (.text+0x0): multiple definition offoo1' prj/src/main.o:(.text+0x0): first defined here make: * [kernel] Error 1

What is the way which allow to compile and link without errors/warning in the situation i described?


回答1:


From http://gcc.gnu.org/onlinedocs/gcc/Inline.html:

When an inline function is not static, then the compiler must assume that there may be calls from other source files; since a global symbol can be defined only once in any program, the function must not be defined in the other source files, so the calls therein cannot be integrated. Therefore, a non-static inline function is always compiled on its own in the usual fashion.

In other words, without static, it emits a symbol for your inline function. If you happen to define that function in a header and include it in more than one compilation unit, then you end up with multiple (redefined) symbols. If you want to include the definition in the header, you should make it static.




回答2:


I tried it and didn't get any errors

a.h

extern inline void foo1()
{
    return;
}

b.h

extern inline void foo2()
{
    foo1();
    return;
}

main.cpp

#include "a.h"
#include "b.h"

int main() {
    foo1();
    foo2();
    return 0;
}



回答3:


Put the inline definitions in your .h file and in the .c files force an external definition.

For example:

// File: a.h
inline void foo1(void) { /*...*/ }

// File main.c
#include "a.h"

extern inline void foo1(void);

int main(void)
{
    /*...*/   
}


来源:https://stackoverflow.com/questions/15013687/linker-error-inline-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!