extern const char * const指针或extern const char array []导致链接错误

时间:2014-05-19 16:32:45

标签: c++ c ld

这是代码:

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命令:g ++ file1.cc file2.cc -o out 错误链接:

/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 ++版本:4.6.3(Unbuntu / Linaro 4.6.3-1ubuntu5)

谁能帮忙?

1 个答案:

答案 0 :(得分:1)

将您的extern声明放在头文件中,并将其包含在 两个源文件。发生的是file1.cc中的情况, arrayStringconstpointerString有内部联系 (因为那是const个对象的默认值),所以不能这样做 从其他翻译单位看。

或者,当然,您可以定义它们:

extern char const arrayString[] = "arrayString";
extern char const* const constpointerString = "constpointerString";

但总的来说,最好使用标题。