woaidongmao

文章均收录自他人博客,但不喜标题前加-[转贴],因其丑陋,见谅!~
随笔 - 1469, 文章 - 0, 评论 - 661, 引用 - 0
数据加载中……

const在C和C++中的一个区别

一个文件中
    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++都是建议把他放到头文件中去的。

posted on 2006-10-31 17:23 周星星 阅读(4342) 评论(2) 编辑 收藏

评论

# re: const在C和C++中的一个区别 2006-11-10 21:41 路人甲

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

# re: const在C和C++中的一个区别 2007-11-23 16:34 空见

//***a.cpp***
#include <iostream>
extern const int i;
void main ()
{
  std::cout << i;
}
//***b.cpp***
extern const int i = 10;
执行结果:
10
不关extern "C"的事情,正如路人甲所说,是const的内连接特性造成的

posted on 2008-11-19 22:32 肥仔 阅读(562) 评论(0)  编辑 收藏 引用 所属分类: C++ 基础


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理