我希望有一些全球地圖,這應該在很多地方都可以使用,一些常用的小功能。這是我如何組織它。C++程序組織代碼,避免「的多個定義。」
util.h:
#ifndef UTIL_H
#define UTIL_H
#include <unordered_map>
namespace util {
extern std::unordered_map<std::string, short> rgb2short {
{ "000000", 0 },
{ "800000", 1 },
{ "008000", 2 },
{ "808000", 3 },
{ "000080", 4 },
/* ... and so on */
};
short some_util_func() {
/* some util code here */
}
}
#endif
somefile.cpp:
#include "util.h"
/* usage of util::rgb2short and util::some_util_func() */
someotherfile.cpp:
#include "util.h"
/* usage of util::rgb2short and util::some_util_func() */
小樣iler沒有接受,並回答wiith衆多multiple definition of 'util::rgb2short'
等
所以,問題是這樣的util事情應該如何更好地組織。
刪除extern關鍵字 - 你在util.h中提供了一個定義,而不是在外部 – OllieB
你爲什麼試圖在你的頭文件中初始化你的地圖。爲什麼你的函數在你的頭文件中沒有被內聯呢? (對於你想要做的事情,這仍然不是一個合適的解決方案)。 – WhozCraig