Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中使用宏访问数组索引_C - Fatal编程技术网

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

在C中使用宏访问数组索引,c,C,我正在尝试使用宏访问C数组。数组在头文件中声明为extern const,并在源文件中实际定义/初始化。宏位于标题中。然后我想从另一个文件访问数组。另一个文件和定义数组的文件都包含头 我尝试过直接从另一个文件访问阵列,它可以正常工作。如果数组是在头文件而不是单独的C文件中定义的,我也可以成功地使用宏。但是我需要使用宏访问数组,并在单独的源文件中定义数组,而不是在头文件中 这是我在标题中的内容(我们称之为file.h): 在具有数组定义的源中(这是file.c): 在实际要使用阵列的另一个源文件中

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

我尝试过直接从另一个文件访问阵列,它可以正常工作。如果数组是在头文件而不是单独的C文件中定义的,我也可以成功地使用宏。但是我需要使用宏访问数组,并在单独的源文件中定义数组,而不是在头文件中

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

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

在实际要使用阵列的另一个源文件中:

"#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)
}
“#包含文件.h”
对于(uint8 i=0;i
我在链接时遇到问题:“未解决的符号”

如果未解析的符号涉及arr,则意味着您错过了与文件.o的链接

例如:

文件.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
文件.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);
}

但是如果我没有链接到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


etc

请在您的include和/或include real代码周围加引号。还要包括未解析的符号。最后,确保所有源文件确实链接在一起,以便文件可以看到彼此的全局文件。发布用于编译程序的命令行。您在哪里定义数据?(我看到数据[I]在for循环中,但不是声明)。他的评论说它是作为函数参数传递的。完全编译代码将有助于解决这些问题,尽管…
\define get_arr(i)(arr[i])
只是混淆了代码的功能。
get_arr(i)
与直接使用
arr
相比没有任何优势[i]
,但它隐藏了实际变量的使用。
#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 $ 
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