哪个更好 - 使用 extern 或在头文件中声明结构数组并在 C 中的 .c 中定义它

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

在头文件中声明数组结构

ex.h

#include <stdint.h>

typedef struct example_t{
    const char *pStr;
    uint32_t size;
} example_t;

struct example_t array_struct[2];

然后在.c文件中定义它

ex1.c

#include "ex.h"

struct example_t array_struct[2] = {{"hello", 5}, {"world", 5}};

void ex1()
{
   for (int i = 0; i < 2; ++i){
       printf("%s\n", array_struct[i].pStr);
       printf("%u\n", array_struct[i].size);
   } 
}

还可以使用另一个.c文件中定义的结构体数组

ex2.c

#include "ex.h"

void ex2()
{
   for (int i = 0; i < 2; ++i){
       printf("%s\n", array_struct[i].pStr);
       printf("%u\n", array_struct[i].size);
   } 
}

这是一个好的做法还是最好在

extern
中使用
ex2.c
并在
ex1.c
中定义它?

c compilation compiler-optimization
1个回答
0
投票

这个:

struct example_t array_struct[2];

不是声明数组,而是定义数组。当您将 .c 文件链接到可执行文件时,使用此选项将导致多个定义出现编译错误。

要声明它,您需要添加

extern

extern struct example_t array_struct[2];
© www.soinside.com 2019 - 2024. All rights reserved.