【发布时间】:2016-03-17 14:45:25
【问题描述】:
我使用几个文件:main.c assembler.c fileHandlers.c handlers.c 此外,我还有几个头文件,包含常量、函数原型等。在其中一个(“datatypes.h”)中,我定义了一个字符串数组:
#ifndef DATATYPES_H
#define DATATYPES_H
const char *OPCODES = {"str1",..., str15}.
#endif
然后,我在所有文件中都包含了这个标题(因为他们都在某个时候使用它)。
这是我的生成文件:
main: main.o assembler.o filesHandler.o handlers.o
gcc -g -Wall -ansi -pedantic main.o assembler.o filesHandler.o handlers.o -o main
main.o: main.c
gcc -g -c -Wall -ansi -pedantic main.c -o main.o
assembler.o: assembler.c
gcc -g -c -Wall -ansi -pedantic assembler.c -o assembler.o
filesHandler.o: filesHandler.c
gcc -g -c -Wall -ansi -pedantic filesHandler.c -o filesHandler.o
handlers.o: handlers.c
gcc -g -c -Wall -ansi -pedantic handlers.c -o handlers.o
当我尝试编译时,我收到以下错误:
gcc -g -c -Wall -ansi -pedantic assembler.c -o assembler.o
gcc -g -c -Wall -ansi -pedantic filesHandler.c -o filesHandler.o
filesHandler.c: In function ‘readFile’:
filesHandler.c:14:10: warning: unused variable ‘addressing’ [-Wunused-variable]
char addressing[MAXWORD];
^
gcc -g -Wall -ansi -pedantic main.o assembler.o filesHandler.o handlers.o -o main
assembler.o:(.data+0x0): multiple definition of `OPCODES'
main.o:(.data+0x0): first defined here
filesHandler.o:(.data+0x0): multiple definition of `OPCODES'
main.o:(.data+0x0): first defined here
handlers.o:(.data+0x0): multiple definition of `OPCODES'
main.o:(.data+0x0): first defined here
collect2: error: ld returned 1 exit status
make: *** [main] Error 1
现在,我知道由于某种原因,数组在预处理后被多次定义,但我不知道为什么。 我阅读了关于#include 守卫的维基百科文章,以及更多资源。他们都指示照我做的那样做,但它不起作用。
抱歉加载了这么多数据,但希望能避免不必要的跟进。
谢谢, 埃拉德
【问题讨论】:
-
第二行
#include DATATYPES_H应该是#define DATATYPES_H。如果标志没有定义,我们还没有被包含,所以定义它。如果它被定义,我们已经被包含过一次,所以什么都不做。 -
抱歉,我打错了问题。在文件中它是#define,而不是#include,但它仍然不起作用。我解决了这个问题。
-
你可以让 OPCODES 本身为 const。
const char * const OPCODES = ....
标签: c++ c header include-guards