C内联函数生成未定义符号错误 [英] C inline function generates Undefined symbols error

查看:81
本文介绍了C内联函数生成未定义符号错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了有关此链接的多个搜索结果,但仍然没有得到: https://gcc.gnu.org/gcc-5/porting_to.html

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;
}

我要让编译器内联 add .没有其他翻译单位,这是唯一的翻译单位.为什么会给我一个未定义符号链接器错误?

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?

在此过程中,我继续阅读 inline add() extern inline add()之间的区别.我以为 C 中的所有功能默认情况下都是 extern ?

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?

错误信息:

$clang 0.c
Undefined symbols for architecture x86_64:
  "_add", referenced from:
      _main in 0-1cc8ba.o

推荐答案

来自C标准(6.7.4函数说明符)

From the C Standard (6.7.4 Function specifiers)

  1. ...如果翻译中功能的所有文件范围声明单位包括不带extern的内联函数说明符,则该翻译单元中的定义是内联定义.一个内联定义不为功能,并且不禁止在另一个外部定义翻译单位.内联定义为外部定义,翻译人员可以使用该外部定义来实现调用同一翻译单元中的函数.未指定对该函数的调用是使用内联定义还是外部定义.
  1. ...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.

为避免错误,请使用存储说明符 static extern .

To avoid the error use the storage specifier either static or extern.

例如

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

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

这篇关于C内联函数生成未定义符号错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆