Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2315225
  • 博文数量: 527
  • 博客积分: 10343
  • 博客等级: 上将
  • 技术积分: 5565
  • 用 户 组: 普通用户
  • 注册时间: 2005-07-26 23:05
文章分类

全部博文(527)

文章存档

2014年(4)

2012年(13)

2011年(19)

2010年(91)

2009年(136)

2008年(142)

2007年(80)

2006年(29)

2005年(13)

我的朋友

分类: C/C++

2009-08-25 16:09:55

======== x.cpp =========
void print_it();
char const hello[] = "asdf";
int main(int argc, char *argv)
{
    print_it();
    return 0;
}

======= y.cpp =========

#include

extern char const hello[1] ;
void print_it()
{
  printf("string = %s\n", hello );
}

链接时出现下面的错误:
y.obj : error LNK2019: unresolved external symbol "char const * const hello" (?hello@@3QBDB) referenced in function "void __cdecl print_it(void)" (?print_it@@YAXXZ)

原因就是C++中, const变量的默认linkage 规则变了. 要消除上面的错误, 要么使用extern "C", 使它回到C语言的规则中, 要么在x.cpp中 hello的定义处显式地加上extern.

这是在C++ templates一书中, 8.3.3 小节中一句话的怀疑引起的:
template
class Message;

extern char const hello[] = "Hello, World!";

Message* hello_msg;

Note the need for the extern keyword because otherwise a const array variable would have internal linkage.

因为记得文件范围内的函数和变量默认都是外部链接.

阅读(1093) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~