0%

Why cannot use linux as varaible name?

StackOverflow看到的。
這段程式,在GCC和Clang會失敗,而在VC正常運作。

1
2
3
4
5
int main()
{
int linux = 1;
return 0;
}

gcc -E下去看的結果如下

1
2
3
4
5
int main()
{
int 1 = 1;
return 0;
}

這是由於在未標準化的年代,像是unix,linux等字都會採到地雷。
不過可以用 gcc -std=c89強讓他走標準規範編譯。

可以看到

1
2
3
4
5
6
7
8
9
$ cpp --std=c89 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1
$ cpp --std=gnu89 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1
#define linux 1

在gnu89裡面GCC自己加了linux的定義下去了。注意這邊的cppThe C Preprocessor,跟C++無關。
-dM來印出所有被Preprocessor定義的值。
既然知道Preprocessor定一些什麼值之後,就可以順利避開陷阱了。