b.c fails to compile but
b.cpp can be compiled. I don't quite understand the difference of extern between C and C++. Could anybody help explain why
b.c does not work but
b.cpp does? Thanks.
$ cat b.c extern int b; int a = b; $ gcc -g -Wall -pedantic -c -o b.o b.c b.c:4:9: error: initializer element is not a compile-time constant int a = b; ^ 1 error generated. $ cat b.cpp extern int b; int a = b; $ g++ -g -Wall -pedantic -c -o b.o b.cpp $ ls -g b.o -rw-r--r-- 1 staff 2640 Jan 5 10:22 b.o
There is no significant difference between
extern variables in C and C++. What is different, is the rule for valid initializers. In C, the initializer of a variable with static storage duration must be a compile time constant. In C++, it can be pretty much any expression (including a complicated function call).