I am reading "C++ primer plus". In Chapter 9, it talks about the difference between C++ and C when dealing with const modifier:
"In C++ (but not C), the const modifier alters the default storage classes slightly. Whereas a global variable has external linkage by default, a const global variable has internal linkage by default.
...
If global const declaration had external linkage as regular variable do, this would be an error because you can define a global variable in one file only. That is, only one file can contain the proceding declaration, and the other files have to provide reference declarations using the extern keywords."
I tried to test this claim with the following program:
file.h:
using namespace std;
const char *constant = "Magic";
file1.cpp
#include <iostream>
#include "file.h"
extern void file2();
int main(){
cout << "constant = " << constant << endl;
file2();
}
file2.cpp
#include <iostream>
#include "file.h"
void file2(){
cout << "file2 constant = " << constant << endl;
}
Makefile:
CFLAGS = -Wall -g
INCLUDE = file.h
src = file2.cpp file1.cpp
all: $(src) $(INCLUDE)
g++ $(CFLAGS) -o file $(src)
clean:
rm -f file
When I do make, i get the following error message:
g++ -Wall -g -o file file2.cpp file1.cpp
/tmp/ccdl16Tw.o:(.data+0x0): multiple definition of `constant'
/tmp/ccA3ZEHa.o:(.data+0x0): first defined here
collect2: error: ld returned 1 exit status
make: *** [all] Error 1
gcc version 4.8.2
UPDATE:
If I do
char* const constant = "Magic";
Then make will give me this warning:
g++ -Wall -g -o file file2.cpp file1.cpp
In file included from file2.cpp:2:0:
file.h:3:24: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
char* const constant = "Magic";
^
In file included from file1.cpp:2:0:
file.h:3:24: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
char* const constant = "Magic";
extern const char *constant;
in the header, and e.gconst char *constant = "Magic";
in one of the translation units? Globals are still different when used outsideclass
/struct
declaratons.const
should have internal linkage, so the linker should not complain about duplicate symbols.const
should have internal linkage", which is obviously wrong, unless specified along astruct
orclass
alsostatic
has it's meanings in c++, that differ from c.const
seems to have internal linkage by default (no need forstatic
), I don't have the standard in front of me, but I tried OP's program with aconst constant = 10;
and the linker doesn't complain about duplicates anymore. The problem here is that the pointer is notconst
, as pointed by @user2079303 answer