使用C中的宏访问数组索引

时间:2019-04-30 21:37:49

标签: c

我正在尝试使用宏访问C数组。该数组在头文件中声明为extern const,并在源文件中实际定义/初始化。宏在标题中。然后,我想从另一个文件访问数组。另一个文件和定义数组的文件都包括头文件。

我尝试直接从另一个文件访问数组,并且它可以工作。如果数组是在标头中定义的,而不是在单独的C文件中定义的,我也可以成功使用宏。但是我需要使用宏访问该数组,并在一个单独的源文件(而不是标题)中定义该数组。

这是标题中的内容(我们称它为file.h):

#define SIZE 10

#define get_arr(i)     (arr[i])

extern const uint8 arr[SIZE];

在具有数组定义的源文件中(这是file.c):

"#include file.h"

const uint8 arr[SIZE] = {0};

在另一个实际要使用数组的源文件中:

"#include file.h"

for(uint8 i = 0; i<SIZE; i++) {
   Data[i] = get_arr(i); //Data is a pointer passed as a parameter to a function)
}

当我尝试构建时,链接出现问题:“未解决的符号”。

1 个答案:

答案 0 :(得分:2)

  

链接时出现问题:“未解析的符号”。

如果未解决的符号与 arr 有关,则意味着您错过了与 file.o

的链接

例如具有:

file.h

#ifndef FILE_H
#define FILE_H

typedef unsigned char uint8;

#define SIZE 10

#define get_arr(i)     (arr[i])

extern const uint8 arr[SIZE];

#endif

file.c

#include "file.h"

const uint8 arr[SIZE] = {0};

main.c

#include "file.h"

void fill(uint8 * Data)
{
  for(uint8 i = 0; i<SIZE; i++) {
    Data[i] = get_arr(i); //Data is a pointer passed as a parameter to a function)
  }
}

int main()
{
  uint8 a[SIZE];
  fill(a);
}

如果我编译并链接所有文件,则无论如何都不会出错:

pi@raspberrypi:/tmp $ gcc file.c main.c 
pi@raspberrypi:/tmp $ 

pi@raspberrypi:/tmp $ gcc -c main.c
pi@raspberrypi:/tmp $ gcc -c file.c
pi@raspberrypi:/tmp $ gcc main.o file.o
pi@raspberrypi:/tmp $ 

但是,如果我错过了与file.o的链接:

pi@raspberrypi:/tmp $ gcc main.c
/tmp/ccG9WO0e.o : Dans la fonction « fill » :
main.c:(.text+0x60) : référence indéfinie vers « arr »
collect2: error: ld returned 1 exit status

pi@raspberrypi:/tmp $ gcc -c main.c
pi@raspberrypi:/tmp $ gcc -c file.c
pi@raspberrypi:/tmp $ gcc main.o
main.o : Dans la fonction « fill » :
main.c:(.text+0x60) : référence indéfinie vers « arr »
collect2: error: ld returned 1 exit status