一個(gè)文件中
const int a = 1;
另一個(gè)文件中
extern const int a;
cout << a << endl;
類似的代碼在C中OK,但在C++中沒(méi)能Link通過(guò)。
改為
一個(gè)文件中
extern "C" {
const int a = 1;
}
另一個(gè)文件中
extern "C" {
extern const int a;
cout << a << endl;
}
在C++中也沒(méi)能Link通過(guò)。
[全局變量]給我的解答是:
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.
于是我改為
一個(gè)文件中
extern "C" const int a = 1;
另一個(gè)文件中
extern "C" const int a;
cout << a << endl;
在C++中OK
改為
一個(gè)文件中
extern "C" {
extern "C" const int a = 1;
}
另一個(gè)文件中
extern "C" {
extern "C" const int a;
}
在C++中也OK
看來(lái) extern "C" 和 extern "C" {} 還是有區(qū)別的^_^
----------------------------------------
const在C和C++中的其他區(qū)別不說(shuō)了,比如const在C++偏向于“常量”,而在C中偏向于“只讀”
簡(jiǎn)單的說(shuō),在C++中,a 是一個(gè)編譯期常量,所以不進(jìn)obj文件,用extern無(wú)效。
在這種情況下,C++都是建議把他放到頭文件中去的。
posted on 2006-10-31 17:23 周星星 閱讀(4342) 評(píng)論(2) 編輯 收藏
評(píng)論
# re: const在C和C++中的一個(gè)區(qū)別 2006-11-10 21:41 路人甲
記得c++編程思想第1卷中好象講過(guò)這個(gè)問(wèn)題,c++中const是內(nèi)連接的.
# re: const在C和C++中的一個(gè)區(qū)別 2007-11-23 16:34 空見(jiàn)
//***a.cpp***
#include <iostream>
extern const int i;
void main ()
{
std::cout << i;
}
//***b.cpp***
extern const int i = 10;
執(zhí)行結(jié)果:
10
不關(guān)extern "C"的事情,正如路人甲所說(shuō),是const的內(nèi)連接特性造成的