c - 如何在多个文件中使用内联函数

标签 c gcc optimization linker inline

我的项目有以下4个文件:main.crcm.hrcm.cqueue.c .

rcm.h 中,我声明了 rcm.cqueue.c 中实现的所有函数。

rcm.c 看起来像:

#include "rcm.h"

void rcm (void) {

  Queue *Q = init(10);

  /* Some other stuff */
}

queue.c` 看起来像:

#include "rcm.h"

extern inline Queue* init(int n) {
  return malloc(sizeof(Queue*);
}

rcm.h:

#ifndef __RCM__
#define __RCM__

typedef struct queue { /*...*/ } Queue;

void rcm( void );

inline Queue* init( int n );
#endif

编译时我收到警告

 gcc-7 -O0 -c rcm.c -o rcm.o
 In file included from rcm.c:15:0:
 rcm.h:58:15: warning: inline function 'init' declared but never defined
 inline Queue* init(int size);
               ^~~~
 gcc-7    -c queue.c -o queue.o
 gcc-7 main.c lib/rcm.o queue.o -o main
In file included from main.c:4:0:
inc/rcm.h:58:15: warning: inline function 'init' declared but never defined
 inline Queue* init(int size);
           ^~~~

但是,当我没有将 init() 声明为 inline 时,可以正常编译。

最佳答案

inline Queue* init( int n );

为了使编译器能够内联函数,它必须知道函数的代码。如果没有这些知识,编译器必须发出对该函数1的调用。因此发出警告。为了在多个模块中使用内联函数,您可以在 header 中将其定义为:

static inline Queue* init (int n)
{
    /* code here */
}

比照。例如GCC documentation for inline .

警告的原因是您希望函数内联,但您向编译器隐藏了代码:main.c 包含声明内联函数的 header ,但在该编译中单元,init 没有定义(实现)。 1 编译器内置的函数除外。在这种情况下,您不必自己提供代码,编译器具有有关它的内置知识。

关于c - 如何在多个文件中使用内联函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60038903/

相关文章:

c - 为什么我们需要一个未使用的字符数组才能成功绑定(bind)?

c++ - 你如何在c/c++中顺序创建伪随机数?

java - 你能帮我实现 Clarke 和 Wright 算法吗?

javascript - 在 JavaScript 中创建集合(相同类型的唯一元素)时,通常使用什么作为键的值?

c - 在用 C 编写一个简单的程序时遇到问题,有什么建议吗?

c++ - 不能在带有 try/catch 的构造函数初始化列表中使用统一初始化

c - -mini-xml 中未找到 lmxml 库?

c - Flycheck 和 Clutter - 我该如何设置?

javascript - 选择最佳样本集来近似具有预定样本数的曲线?

从一段单词创建哈希表和节点