C - 访问链接文件中的不完整类型

标签 c arrays linker constants incomplete-type

我在用 C 链接多个文件时遇到问题。我想在编译时定义一个表示数组长度的常量,但用户不必每次都在他们的文件中实现它。

这里是要点:

data.h - 定义一些常量

extern const int data[];
extern const int DATA_SIZE;
//other functions, not relevant
int get_second_item(void);

library_data.c - 实现了data.h中的一些功能

#include "data.h"
const int DATA_SIZE = sizeof(data) / sizeof(data[0]); 
//can't compile because data is an incomplete type and hasn't been defined yet

int get_second_item(void) 
{
    return data[1];
}

public_data.c - 用户用他们的数据改变这个。

#include "data.h"
const int data[] = {1, 2, 3};

library_data.cdata.h 首先被编译为 .o 文件,以及#include data.h 的其他库文件,因此需要使用 DATA_SIZE。移动

const int DATA_SIZE = sizeof(data) / sizeof(data[0]) 

public_data.c 当然可以,但这不是一个完美的解决方案。

最佳答案

您不能在未指定大小的 extern 数组上使用 sizeof(例如 extern const int data[];)

来自 http://c-faq.com/decl/extarraysize.html :

An extern array of unspecified size is an incomplete type; you cannot apply sizeof to it. sizeof operates at compile time, and there is no way for it to learn the size of an array which is defined in another file.

You have three options:

  1. Declare a companion variable, containing the size of the array, defined and initialized (with sizeof) in the same source file where the array is defined:

    file1.c: file2.c:

    int array[] = {1, 2, 3}; extern int array[];
    int arraysz = sizeof(array); extern int arraysz;

    (See also question 6.23.)

  2. #define a manifest constant for the size so that it can be used consistently in the definition and the extern declaration:

    file1.h:

    #define ARRAYSZ 3
    extern int array[ARRAYSZ];

    file1.c: file2.c:

    #include "file1.h" #include "file1.h"
    int array[ARRAYSZ];

  3. Use some sentinel value (typically 0, -1, or NULL) in the array's last element, so that code can determine the end without an explicit size indication:

    file1.c: file2.c:

    int array[] = {1, 2, 3, -1}; extern int array[];

关于C - 访问链接文件中的不完整类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48413313/

相关文章:

c++ - 带有双移位和以下移位运算的 C/C++ 除法

python - python 2.7中使用bytearray向中继板串口发送十六进制命令

c - 目前有什么好的 UNIX 编译器/链接器选项的跨平台引用吗?

将函数转换为使用迭代

c - scanf() 格式字符串中尾随空格有何影响?

javascript - 将原生数组/对象转换为 Ember.Array/Ember.Object 的最佳实践

javascript - 如何使用对象的键返回过滤后的对象数组

linux - 无法识别共享库文件格式

c++ - Unresolved external 问题 [构造函数]

c - 如何在 C 中使用 execvp() 对文件进行排序并写入另一个文件