here is code:
file1.cc
#include <stdio.h>
const char *pointerString = "pointerString";
const char arrayString[] = "arrayString";
const char* const constpointerString = "constpointerString";
extern void printString();
int main(void)
{
printString();
return 0;
}
file2.cc
#include <stdio.h>
extern const char *pointerString;
extern const char arrayString[];
extern const char* const constpointerString;
void printString()
{
printf("pointerString: %s\n", pointerString);
printf("arrayString: %s\n", arrayString);
printf("constpointerString: %s\n", constpointerString);
}
complite command: g++ file1.cc file2.cc -o out error link:
/tmp/cczatCe9.o: In function `printString()':
file2.cc:(.text+0x1f): undefined reference to `arrayString'
file2.cc:(.text+0x30): undefined reference to `constpointerString'
collect2: ld returned 1 exit status
g++ version: 4.6.3(Unbuntu/Linaro 4.6.3-1ubuntu5)
anyone can help??
Put your extern declarations in a header file, and include it in
both source files. What's happening is that in file1.cc,
arrayString and constpointerString have internal linkage
(because that is the default for const objects), and so can't
be seen from other translation units.
Alternatively, of course, you can define them:
extern char const arrayString[] = "arrayString";
extern char const* const constpointerString = "constpointerString";
But in general, it is better to use the header.
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