頁:
[1]
關於多檔案與namespace的問題
本帖最後由 在那裡 於 2018-8-2 06:05 PM 編輯最近小弟在使用namespace時遇到了一個問題
小弟開了一個空專案,裡面有三個檔案
首先是namespace定義的NamespaceDeclare.h,內部宣告各Namespace以及函式的原型
以及宣告函式內容的NamespaceDeclare.cpp
最後是主程式的main.cpp
分別如下
-----NamespaceDeclare.h-----
#ifndef NAMESPACEDECLARE_H_
#define NAMESPACEDECLARE_H_
#include <iostream>
namespace My
{
void show(const int);
//int My_int; //it is problem
}
void show(const int);
#endif // NAMESPACEDECLARE_H_
-----End-----
-----NamespaceDeclare.cpp-----
#include <iostream>
#include "NamespaceDeclare.h"
namespace My
{
void show(const int content)
{ //點擊問題(multiple definition of "My::My_int")後跳來這
std::cout << "Namepsace:My\n"
<< content << std::endl;
}
}
extern void show(const int content)
{
std::cout << "Namespace:global\n"
<< content << std::endl;
}
-----End-----
-----main.cpp-----
#include <iostream>
#include "NamespaceDeclare.h"
int main()
{ //點擊問題(first defined here)跳來這
show(123);
std::cout << std::endl;
My::show(123);
return 0;
}
-----End-----
每次當小弟在NamespaceDeclare.h的namespace My中加上int My_int時(就是去掉//)
總會跳出
multiple definition of "My::My_int"
first defined here
點擊這問題的話則會指向NamespaceDeclare.cpp 裡的"//點擊問題後跳來這"
如果沒有加上My_int的話運行則是正常……請問小弟到底哪裡出錯了???
...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div><div></div> 就是你把一個 int My_int 的定義放在 header file
但是這個 header file 被多個 .cpp 引用違反了 ODR
正確來說 header file 放宣告 .cpp 放定義才對 caoh 發表於 2018-8-4 05:00 PM static/image/common/back.gif
就是你把一個 int My_int 的定義放在 header file
但是這個 header file 被多個 .cpp 引用違反了 ODR
正確 ...
哦!所以說因為我在 NamespaceDeclare.cpp 中include標頭檔一次,
又在main.cpp中include標頭檔一次,
造成重複宣告。
……那麼該怎麼避免這情況呢?
還是說標頭檔不應該宣告變數?...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div> 標頭檔放宣告 extern int My_int;
實作檔放定義 int My_int;
頁:
[1]