在头文件中声明数组结构
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
中定义它?
这个:
struct example_t array_struct[2];
不是声明数组,而是定义数组。当您将 .c 文件链接到可执行文件时,使用此选项将导致多个定义出现编译错误。
要声明它,您需要添加
extern
:
extern struct example_t array_struct[2];