返回信息流// foo.h
inline int foo(int a, int b) {
return a*a + b*b;
}
// main.c
#include <stdio.h>
#include "foo.h"
int main() {
printf("%d\n", foo(3, 4));
return 0;
}
// main.cpp
#include <cstdio>
#include "foo.h"
int main() {
std::printf("%d\n", foo(3, 4));
return 0;
}
编译:
$ gcc -o main-c main.c
/tmp/cck1bvhw.o: In function `main':
main.c:(.text+0xf): undefined reference to `foo'
collect2: error: ld returned 1 exit status
$ g++ -o main-c++ main.c
$ ./main-c++
25
为什么C语言会出现链接错误,而C++却可以正常编译?
如何让C也能正常编译呢?(仍然要让foo为内联函数)
这是一条镜像帖。来源:北邮人论坛 / cpp / #95965同步于 2017/8/12
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
[C语言也惊喜]内联函数链接错误?
nuanyangyang
2017/8/12镜像同步20 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
暖婶解决了没?
【 在 nuanyangyang (暖羊羊) 的大作中提到: 】
: [code=c]
: // foo.h
: inline int foo(int a, int b) {
: ...................
通过『我邮2.0』发布
1、C和C++是两种不同的语言,inline是C++关键字,C99时候才引入到C语言里。
2、关于为什么,可以看C标准:
Any function with internal linkage can be an inline function. For a function with external linkage, the following restrictions apply: If a function is declared with an inline function specifier, then it shall also be defined in the same translation unit. 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.
inline、static inline、extern inline。
3、这种抠语法的问题没啥意义,有那时间不如多解决点实际的工程问题。
额 看了下C99有
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.
所以如果不对main.c中的foo函数用extern关键字进行修饰,那么在生成的.o的符号表中_foo符号并不能在.h中找到实现,因此只能推迟到linking阶段去等待外部的库进行链接,而外部的库并没有提供_foo符号的导出,所以最后表现在linking失败.而通过声明extern关键字表明该函数在别的地方有定义,在生成.o的过程中就找到了,链接过程正常.当然也可以在.h中声明函数为static的来解决这个问题.说到底就是为了使得inline函数有进行符号导出.
至于C++怎么回事,猜测是编译过程拒绝了inline要求,因为发现main.cpp中有需要用到它,所以最后就直接linking成功了...不知道说的对不对,望暖神指教