Chinaunix首页 | 论坛 | 博客
  • 博客访问: 913800
  • 博文数量: 158
  • 博客积分: 4380
  • 博客等级: 上校
  • 技术积分: 2367
  • 用 户 组: 普通用户
  • 注册时间: 2006-09-21 10:45
文章分类

全部博文(158)

文章存档

2012年(158)

我的朋友

分类: C/C++

2012-11-21 10:19:13

一个文件中
    const int a = 1;
另一个文件中
    extern const int a;
    cout << a << endl;
类似的代码在C中OK,但在C++中没能Link通过。

改为
一个文件中
extern "C" {
    const int a = 1;
}
另一个文件中
extern "C" {
    extern const int a;
    cout << a << endl;
}
在C++中也没能Link通过。

给我的解答是:

C and C++ const Differences
When you declare a variable as const in a C source code file, you do so as:

const int i = 2;

You can then use this variable in another module as follows:

extern const int i;

But to get the same behavior in C++, you must declare your const variable as:

extern const int i = 2;

If you wish to declare an extern variable in a C++ source code file for use in a C source code file, use:

extern "C" const int x=10;

to prevent name mangling by the C++ compiler.

于是我改为
一个文件中
    extern "C" const int a = 1;
另一个文件中
    extern "C" const int a;
    cout << a << endl;
在C++中OK

改为
一个文件中
extern "C" {
    extern "C" const int a = 1;
}
另一个文件中
extern "C" {
    extern "C" const int a;
}
在C++中也OK

看来 extern "C" 和 extern "C" {} 还是有区别的^_^

----------------------------------------

const在C和C++中的其他区别不说了,比如const在C++偏向于“常量”,而在C中偏向于“只读”

简单的说,在C++中,a 是一个编译期常量,所以不进obj文件,用extern无效。
在这种情况下,C++都是建议把他放到头文件中去的。

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

网友评论2012-11-21 10:20:10

空见
//***a.cpp***
#include <iostream>
extern const int i;
void main ()
{
  std::cout << i;
}
//***b.cpp***
extern const int i = 10;

执行结果:
10
不关extern "C"的事情,正如路人甲所说,是const的内连接特性造成的

网友评论2012-11-21 10:20:00

路人甲

记得c++编程思想第1卷中好象讲过这个问题,c++中const是内连接的.