c - 如何在 C 中使用外部 union 数组?

标签 c arrays extern unions

我想使用类似于 chux 建议的 union 数组

union {
  uint8_t u8[12];
  uint16_t u16[6];
} *array_u;

array_u = calloc(1, sizeof *array_u);
assert(array_u);

printf("array_u->u8[0] = %" PRIu8 "\n", array_u->u8[0]);

array_u->u16[0] = 1234;
printf("array_u->u16[0] = %" PRIu16 "\n", array_u->u16[0]);
...

来源:Is it okay to store different datatypes in same allocated memory in C?

我想将它用作不同文件需要访问它的全局数组。所以我尝试了 globals.h:

extern union {
    uint8_t u8[12];
    uint16_t u16[6];
} *array_u;

我想在这个文件 memory.c 中分配和释放它:

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdlib.h>
#include "globals.h"

void allocate_array_u(void){
    array_u = calloc(1, sizeof *array_u);
}

很遗憾,我收到一个 error LNK2001: unresolved external symbol array_u

我该如何解决?

解决方案: 我忘记在 main.cmemory.c 中定义 union :

array_u_t *array_u;

最佳答案

除了将array_u 声明为extern 之外,您还需要定义 变量。 extern 只是说在其他地方找到定义。该定义需要存在于某处。

尝试以下操作。

改变 globals.h 如下:

typedef union {
    uint8_t u8[12];
    uint16_t u16[6];
} array_u_t;

extern array_u_t *array_u;

memory.c中定义array_u如下:

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdlib.h>
#include "globals.h"

array_u_t *array_u; // <---------------- definition

void allocate_array_u(void){
    array_u = calloc(1, sizeof *array_u);
}

关于c - 如何在 C 中使用外部 union 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34561171/

相关文章:

c - 适当的外部变量声明和定义

c - 为什么在我使用归并排序时,一个额外的元素被添加到我的 void** 数组中?

java - 如何定义 swig typemap 以将 unsigned char* 返回给 java

c++ - 将一维, "flattened"索引转换为N维数组的N维 vector 索引

Java:将txt文件放入第二个数组中

c++ - 从不同 VS2010 项目中的 C++ 代码调用 C 函数时出现链接器错误

c - GetObject 在文本光标上失败

c - 我怎样才能使素数分解的输出更实用?

C - 字段类型不完整

c++ - extern const inside namespace 和 static const 类成员之间的区别?