gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:48:33 25 4
gpt4 key购买 nike

我在用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com