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

问题描述 投票:0回答:1

我的项目有以下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时,可以正常编译。

c gcc linker compiler-construction inline
1个回答
0
投票

inline Queue* init( int n );

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

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

cf。例如GCC documentation for inline

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

© www.soinside.com 2019 - 2024. All rights reserved.