如何在没有单独的源文件的情况下定义外部符号?

时间:2014-10-22 16:42:30

标签: c++ c++11 linker external

一个非常简单的类foo实现了单例模式:(注意行标记供以后参考)

struct foo{
    //int value_;        //(1)
    static foo instance_;
    static void init(){
        instance_ = foo();
    }
    static foo& instance(){
        return instance_;
    }
};

int _tmain(int argc, _TCHAR* argv[]) //oddity of VS/Windows
{
    foo::init();
    //auto inst0 = foo::instance();    //(2)
    //auto inst1 = foo::instance_;     //(3)
    return 0;
}

当它保持这样时,它编译得很好。下表将显示链接错误发生的时间:

|  (1)  |  (2)  |  (3)  |  error?  |
====================================
|   N   |   N   |   N   |    N     |
|   Y   |   -   |   -   |    Y     |
|   -   |   Y   |   -   |    Y     |
|   N   |   N   |   Y   |    N     |

Y = Yes, N = No, - = doesn't matter

遇到的错误是:

error LNK2001: unresolved external symbol "public: static struct foo foo::instance_"

当我将foo移动到单独的标题并添加包含标题和定义外部符号的源文件时,这当然会逐渐消失:

foo foo::instance_ = foo();

出现两个问题:

  1. 当第(3)行是唯一使用过的时候,为什么没有链接错误?我的猜测是某种优化。

  2. 如果= foo()声明不起作用,如何在不添加源文件的情况下解决此问题?使用instance_,因为只允许const个整数类型的成员。

0 个答案:

没有答案