admin管理员组文章数量:1571372
问题描述
一段很简单的代码,使用了内联函数,编译竟然报错。在这里记一下加深记忆。
#include <stdio.h>
#include <stdbool.h>
inline int sum(int a, int b){
return a+b;
}
int main(int argc, char * argv[]){
int a,b;
a=3;b=5;
printf("sum(%d,%d) is %d\n", a, b, sum(a,b));
return 0;
}
编译结果
$ gcc test.c
D:\msys64\tmp\cc49OSY4.o:test.c:(.text+0x2e): undefined reference to `sum'
collect2.exe: error: ld returned 1 exit status
我用的是MinGW的64位gcc
$ which gcc
/mingw32/bin/gcc
$ gcc --version
gcc.exe (Rev3, Built by MSYS2 project) 9.1.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
解决办法
1)使用 -O 编译选项
在论坛上找到一个帖子,加上-O
之后果然行了
$ gcc -O test.c -o test
$ ./test.exe
sum(3,5) is 8
2)修改代码
另一种说法是inline关键字必须放在定义中,原型声明中不能使用inline,给内联函数单独提供了一个不带inline的原型声明,编译就能通过了。但是总觉得这样太罗嗦了。
#include <stdio.h>
#include <stdbool.h>
int sum(int a, int b);
inline int sum(int a, int b){
return a+b;
}
$ gcc test.c -o test
$ ./test.exe
sum(3,5) is 8
版权声明:本文标题:gcc 内联函数编译报错 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1727689846a1125742.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论