3

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

2
  • const object has internal linkage, so the variables are not visible outside. Commented May 19, 2014 at 16:47
  • thinks anyway, i get answer from http://stackoverflow.com/questions/14977058/extern-const-char-const-some-constant-giving-me-linker-errors Commented May 20, 2014 at 2:11

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.