问题描述
一段很简单的代码,使用了内联函数,编译竟然报错。在这里记一下加深记忆。
#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