The following piece of code working fine:
#include <stdio.h>
extern int foo; // Without constant
int foo = 42;
int main()
{
printf("%d\n",foo);
return 0;
}
But, the following piece of code give an error:
#include <stdio.h>
const extern int foo; // With constant
int foo = 42;
int main()
{
printf("%d\n",foo);
return 0;
}
So, why does const extern give an error?
Standard says:
C11-§6.7/4
All declarations in the same scope that refer to the same object or function shall specify compatible types
const int and int are not compatible for the same object foo in the same scope.
These two declarations are contradictory:
const extern int foo; // With constant
int foo = 42;
The first one declares foo as const, and the second one declares it as non const.
Error messages:
prog.cpp:4:5: error: conflicting declaration
‘int foo’ int foo = 42;
^~~
prog.cpp:3:18: note: previous declaration as ‘const int foo’
const extern int foo; // With constant
^~~
You say foo is const and then try to change its constness with the other declaration.
Do this and you should be fine.
const extern int foo; // With constant
const int foo = 42;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With