How can I create a string constant in gcc 4.9.2?
我在带有 GCC 4.9.2 的 Arch Linux 上运行,我在编译以下代码时遇到了问题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #ifndef WORLD_H #define WORLD_H #include <string.h> #include <stdio.h> //#include"removeBuffering.h" //World dimensions #define WORLD_WIDTH 80 #define WORLD_HEIGHT 20 //World block types #define FLAT_LAND '-' //Instructions #define MOVE_UP 'w' #define MOVE_DOWN 's' #define MOVE_RIGHT 'd' #define MOVE_LEFT 'a' #ifndef WIN32 #define COMMAND"clear" //Clears a linux console screen #else #define COMMAND"cls" //Clears a windows console screen #endif #define wipe() system( COMMAND ) |
它适用于我的 koding.com VM,它使用 GCC 4.8.2,但在我的本地机器上,它会生成以下错误:
1 2 | include/world.h:17:17: error: expected declaration specifiers or ‘...’ before string constant #define COMMAND"clear" //Clears a linux console screen |
我认为这是由于 GCC 4.9 中的某种变化,但我似乎找不到任何关于它的好信息,所以任何帮助将不胜感激
在我给出自己的答案之前,我想先概述一下我的代码在生成上述错误消息时的外观。这是world.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #ifndef WORLD_H #define WORLD_H #include <string.h> #include <stdio.h> //#include"removeBuffering.h" //World dimensions #define WORLD_WIDTH 80 #define WORLD_HEIGHT 20 //World block types #define FLAT_LAND '-' //Instructions #define MOVE_UP 'w' #define MOVE_DOWN 's' #define MOVE_RIGHT 'd' #define MOVE_LEFT 'a' #ifndef WIN32 #define COMMAND"clear" //Clears a linux console screen #else #define COMMAND"cls" //Clears a windows console screen #endif int cursorXPos; int cursorYPos; char world[WORLD_HEIGHT][WORLD_WIDTH+1]; //Space for null terminator void initializeWorld(); void printWorld(); void getInput(); //void printHelp(); #endif |
这是world.c(我已经清空了函数以节省空间)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include"world.h" void initializeWorld() { } void printWorld() { } void getInput() { } system(COMMAND); printWorld(); |
这是 GCC 提供的完整错误列表:
1 2 3 4 5 6 7 8 9 10 11 12 13 | In file included from src/world.c:1:0: include/world.h:17:17: error: expected declaration specifiers or ‘...’ before string constant #define COMMAND"clear" //Clears a linux console screen ^ src/world.c:78:10: note: in expansion of macro ‘COMMAND’ system(COMMAND); ^ src/world.c:79:3: warning: data definition has no type or storage class printWorld(); ^ src/world.c:79:3: error: conflicting types for ‘printWorld’ src/world.c:13:6: note: previous definition of ‘printWorld’ was here void printWorld() |
根据我的经验,处理列表中的第一个错误总是一个好主意,所以除了第一个错误之外我没有过多关注,这就是我首先提出这个问题的原因.我最终尝试按照 Carey Gregory 和 immibis 的建议解决后来的错误。
重要的是:
1 2 3 4 5 6 | src/world.c:79:3: warning: data definition has no type or storage class printWorld(); ^ src/world.c:79:3: error: conflicting types for ‘printWorld’ src/world.c:13:6: note: previous definition of ‘printWorld’ was here void printWorld() |
只要我移动了 printWorld()(和 system())的错误函数调用,错误就消失了。
通过