加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么我会收到链接器错误?

发布时间:2020-12-16 09:45:36 所属栏目:百科 来源:网络整理
导读:为什么我会收到链接器错误? /*test.cpp? Andrey Bushman,18 Jun 2013*///--------------------------------------------#include exception#include iostreamusing namespace std;//--------------------------------------------namespace Bushman{//-----
为什么我会收到链接器错误?

/*
test.cpp
? Andrey Bushman,18 Jun 2013
*/
//--------------------------------------------
#include <exception>
#include <iostream>
using namespace std;
//--------------------------------------------
namespace Bushman{
//--------------------------------------------
    class MyClass{
    public:
        MyClass();
    };
//--------------------------------------------
    MyClass::MyClass(){
        void func(); // declaration
        func(); // call
    }
//--------------------------------------------
    void func(){ // definition
        cout << "Ping..." << endl;
    }
}
//============================================
int main()
try{
    namespace B = Bushman;
    B::MyClass a;
}
catch(exception& e){
    cerr << e.what() << endl;
    return 1;
}
catch(...){
    cerr << "Unknown exception." << endl;
    return 2;
}

结果(通过MS Visual Studio 2012):

C:bs13>cl test.cpp /EHsc
Microsoft (R) C/C++ Optimizing Compiler
Version 17.00.51106.1 for x64 Copyright (C) Microsoft Corporation. All
rights reserved.

test.cpp
Microsoft (R) Incremental Linker Version 11.00.51106.1
Copyright (C) Microsoft Corporation. All rights reserved.

/out:test.exe test.obj test.obj : error LNK2019: unresolved external
symbol "void __cdecl func(void)" ( ?func@@YAXXZ) referenced in
function "public: __cdecl Bushman::MyClass::MyClass( void)"
(??0MyClass@Bushman@@QEAA@XZ) test.exe : fatal error LNK1120: 1
unresolved externals

C:bs13>

谢谢.

解决方法

看起来你的编译器错误地将名称引入全局命名空间,而不是C 11 3.5 / 7规定的最里面的封闭命名空间(Bushman):

When a block scope declaration of an entity with linkage is not found to refer to some other declaration,then that entity is a member of the innermost enclosing namespace.

该代码按照GCC:http://ideone.com/PR4KVC的预期编译

您应该能够通过在构造函数的块作用域中声明它之前(或代替)声明函数来解决该错误.但是,我没有访问您的编译器来测试它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读