2

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??

micheal.yxd
  • 118
  • 1
  • 7
  • `const` object has internal linkage, so the variables are not visible outside. – Rakib May 19 '14 at 16:47
  • thinks anyway, i get answer from `http://stackoverflow.com/questions/14977058/extern-const-char-const-some-constant-giving-me-linker-errors` – micheal.yxd May 20 '14 at 02:11

1 Answers1

1

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.

James Kanze
  • 150,581
  • 18
  • 184
  • 329