gcc 内联函数编译报错

问题描述

一段很简单的代码,使用了内联函数,编译竟然报错。在这里记一下加深记忆。

#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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值