我的项目有以下4个文件:main.c
、rcm.h
、rcm.c
和queue.c
.
在 rcm.h
中,我声明了 rcm.c
和 queue.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/