c - 通过内联函数公开静态变量

标签 c

在我的 C 代码中,我想通过内联函数公开静态变量,这样可以避免使用“extern”属性,这是标准 C 中的 OOP。但是我无法编译它。考虑以下代码:

$ cat object.h
inline int get_value(int index);
$ cat object.c
#include "object.h"
static int data_array[32];

inline int get_value(int index) {
    return data_array[index];
}
$ cat app.c 
#include "object.h"
void main(void) {
    int datum;

    datum=get_value(8);
}
$ gcc -c object.c
object.c:5:9: warning: ‘data_array’ is static but used in inline function ‘get_value’ which is not static
  return data_array[index];
         ^
$ ls -l object.o
-rw-rw-r-- 1 niko niko 976 Aug 30 15:56 object.o
$ gcc -c app.c
In file included from app.c:1:0:
object.h:1:12: warning: inline function ‘get_value’ declared but never defined
 inline int get_value(int index);
            ^
$ ls -l app.o
-rw-rw-r-- 1 niko niko 1368 Aug 30 15:56 app.o
$ gcc -o app app.o object.o
app.o: In function `main':
app.c:(.text+0xe): undefined reference to `get_value'
collect2: error: ld returned 1 exit status

是否可以在通过内联函数声明的文件之外以某种方式访问​​静态变量,该函数将内联到正在使用的每个 .c 文件中?当然,我可以只声明变量“extern”:

extern int data_array[];

并直接引用它,但我想通过一个函数来模拟 C 中的 OOP,而不需要函数调用的开销。

最佳答案

您的代码是非法的(在 ISO C 和 GNU C 中):声明为 inline 的函数体必须与对该函数的任何调用出现在同一翻译单元中。但在您的代码中,它不会出现在 app.c 中,这就是您收到 undefined reference 错误的原因。

此外,正如注释中提到的,在 ISO C 中,内联函数也不是静态的,可能不会提及具有内部链接的数组。 (我不知道GNU C在这方面的规则是什么)。

在评论中,您谈论了“CALL 的开销”等内容。但这与 inline 关键字几乎没有关系。如果您使用优化开关,优化器将生成尽可能最快的代码。 inline 关键字的目的是允许函数体出现在头文件中。

一种选择是取消将该函数标记为内联,并在 gcc 中使用-O2 -flto 开关。

另一种选择是使用inline函数,但将函数体放在头文件中。在这种情况下,您还需要使用 extern int data_array[]; 等,因为无法在头文件中定义数组。在执行此选项之前,然后 read this page 。以下是一些与 ISO C 和 GNU C 兼容的代码:

// header file
extern int data_array[];

static inline int get_value(int index)
{
    return data_array[index];
}

// source file
#include "header.h"

int data_array[32];

关于c - 通过内联函数公开静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39237068/

相关文章:

使用 strtok_r 创建 C split 函数 - 就像 perl 和 awk

c - 堆排序无法正常工作

c - 注释风格会影响二进制大小吗?

c - 向 Eclipse 项目添加 C/C++ 特性

字节数与字符数

C IPC等待 child

C 编写一个将字符分类为 ASCII 的程序?

c - 引用外部全局变量惨遭失败

c - 如何将整数转换为字符串?

c - Unix域套接字非阻塞操作在C中监听失败