跨文件共享地图C ++

时间:2018-12-07 05:24:57

标签: c++

我有一个用例,其中我必须创建一个函数指针映射并在各种文件中使用它。我已经在头文件中编写了模板代码,以及用于填充地图的代码。当我不将map定义为静态时,我会收到一条错误消息,指出map的多个定义,因为我将此标头包含在多个cpp文件中。为了避免这种情况,我将地图创建为静态。但是,现在程序由于Seg Fault失败,可能是因为当我开始添加功能时,地图尚未初始化。我怎么解决这个问题?

头文件-

#ifndef KEY_COMPARE__H
#define KEY_COMPARE__H

#include <map>

enum DataType {
    A,
    B,
    MaxType
};

static const int MAX_KEYS = 5;

typedef bool (*Comparator)(uint8*, uint8*);
static std::map<long, Comparator> ComparatorMap; // <--- This is the map

template<typename T, typename... Args>
long GetComparatorKey(T first, Args... args) {
    // Code to return a unique key based on first, args...
}

template <int N, DataType T, DataType... Ts>
struct Comparator {

    Comparator() {
        long comparatorKey = GetComparatorKey(T, Ts...);
        ComparatorMap[comparatorKey] = c1Func; // Seg fault here
    }

    static bool Compare(uint8 *rec1, uint8 *rec2){
        // Function to compare
    }

    static const size_t nKeys_ = Comparator<N+1, T, Ts...>::nKeys_ - 1;
    Comparator<N+1, A, T, Ts...> ci_;
    Comparator<N+1, B, T, Ts...> cs_;

    bool (*c1Func)(uint8*, uint8*) = Compare;
};

/// Other code for base cases and stop recursion

#endif // KEY_COMPARE__H

编辑:

我还尝试创建一个带有map的结构作为静态成员变量,以避免全局变量。即使那样似乎也不起作用。

1 个答案:

答案 0 :(得分:3)

当您将变量定义为static时,意味着内部linkage ,这使得每个translation unit都具有私有性。

即每个源文件都会有自己独特的地图实例。

要使地图成为全局地图并在所有翻译单位之间共享,只需声明地图(使用extern而不是static)。然后在单个源中定义地图(不包含staticextern)。

请注意,通常不建议使用全局变量。

相关问题