使用-std = gnu99和内联函数时编译错误 [英] Compiling error when -std=gnu99 and inline function is used

查看:976
本文介绍了使用-std = gnu99和内联函数时编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code:

#include <stdio.h>
inline int myfunc (int x) {
    return x+3;
}

int main () {

    printf("%d", myfunc(2));
    return 0;
}

当我使用 -std = gnu99 标志(我用gcc编译)不能编译。这是它抛出的错误:

does not compile when I use the -std=gnu99 flag (I am compiling with gcc). This is the error it throws:

gcc -std=gnu99 -c main.c -o main.o
gcc -std=gnu99 main.o -o main
main.o: In function `main':
main.c:(.text+0x15): undefined reference to `myfunc'
collect2: ld returned 1 exit status
make: *** [main] Error 1

编译去没有问题,则省略 -std = gnu99 时。有谁知道为什么链接器抱怨如果 -std = gnu99 使用?

The compilation goes with no problems when -std=gnu99 is omitted. Does anyone know why is the linker complaining if -std=gnu99 is used?

推荐答案

在C99,你需要指定一个声明,您的内联函数像

In C99 you need to specify either a declaration to your inline function like

int myfunc(int);

或让编译器通过指定 -finline-功能 -O3 实际上内联函数。

or allow the compiler to actually inline the function by specifying -finline-functions or -O3.

引用C99标准:

具有内部链接的任何功能,可以是内联函数。对于
  具有外部链接的功能,以下限制
  适用:如果一个函数与内联函数说明符声明,
  然后它也应在相同的翻译单元来定义。如果
  所有翻译文件范围内声明的功能
  单元包括内联函数说明没有extern,这样
  在该转换单元中的定义是内联的定义。一个
  内嵌定义不提供对外部定义
  功能,并且不禁止在另一外部定义
  翻译单元。内联定义提供一种替代的
  外部定义,翻译可以用它来实现任何
  调用在同一翻译单元的功能。 这是
  未指定的函数的调用是否使用内联
  定义或外部定义。

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.

所以编译器就可以使用 MYFUNC 外部定义 - 它不存在,如果你不提供的,因此链接器错误。它为什么preFER选择一个不存在的外部定义?因为你不使用 -finline-功能或包含此标志的优化级别不允许的内联。

So the compiler is free to use the external definition of myfunc - which doesn't exist if you don't provide it, hence the linker error. Why does it prefer to choose a non existing external definition? Because you disallowed inlining by not using -finline-functions or a optimization level which contains this flag.

这篇关于使用-std = gnu99和内联函数时编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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