How to properly inline and use an inline function in C99, correcting link failure?

百般思念 提交于 2019-11-28 03:38:43

问题


Doing cc -std=c99 example.c on the following simplified example.c file:

inline void a()
{
}

int main()
{
   a();

   return 0;
}

gets me:

In function `main':
example.c:(.text+0x7): undefined reference to 'a'
collect2: ld returned 1 exit status

As I understand this has to do with the requirement of C99 standard to demand exactly one more definition for each inline non-static function that is used in cases where the body cannot be inlined? If that is so, I am guessing I could do with static inline instead, but I don't want this to bite me later, so what would be the best course of action here? Obviously, I want to stick to C99 and I want to inline some functions. (Yes, I am aware the compiler usually knows what to inline without being told so, but I have my reasons)


回答1:


Probably you wouldn't have that error when you compile with -O2 or so.

Inline function definitions should go in header files and an extern inline declaration should go in one compilation unit. Do

inline void a(void){
 // empty
}

// in just one .c file
#include "the-file.h"
extern inline void a(void);

BTW, declaring a without void is not a prototype.




回答2:


There's no function prototype, that's all, so the function signature is inferred, and inferred wrong. Add "void a();" to the top of the file, and you're all set.



来源:https://stackoverflow.com/questions/5369888/how-to-properly-inline-and-use-an-inline-function-in-c99-correcting-link-failur

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