C++, good old LNK1169 (and LNK2005) errors

前端 未结 3 952
暖寄归人
暖寄归人 2020-12-22 02:52

I have 4 files, 2 headers and 2 cpp files.

Header file one:

#ifndef complex_2
#define complex_2
#include
#include

using         


        
相关标签:
3条回答
  • Example to repro LNK1169 & LNK2005 with structs: Place the following in the header file:

        Struct Foo
        {
        std::wstring Bar[3]
        };
    
        Foo InitFoo[2]
        {
        {L"ConstBar1Val", L"ConstBar1Val2", L"ConstBar1Val3"},
        {L"ConstBar2Val", L"ConstBar2Val2", L"ConstBar3Val3"}
        };
    

    Solution: Move the initialised struct & arrays to the corresponding cpp file.

    0 讨论(0)
  • 2020-12-22 03:25

    Move the definition of the

    std::ostream & operator<< (ostream &mm, const comp::complex &c)
    

    in one of the CPP files.

    The linker doesn't like this. Personally I'd create a new cpp file for this one too :)

    0 讨论(0)
  • 2020-12-22 03:27

    When you define a standalone function (with a body) in header file you must use inline (functions defined within class definition are inline by default).

    E.g. in header file one must be :

    inline ostream& operator<< (ostream &mm, const complex &c){
        if(c.get_im() >= 0){
            mm << "(" << c.get_re() << " + " << c.get_im() << "i)" << endl;
        }
        if(c.get_im() < 0){
            mm << "(" << c.get_re() << " - " << -(c.get_im()) << "i)" << endl;
        }
        return mm;
    }
    

    Otherwise you will define this function in each translation unit that includes that header and thus may get multiple definition error.

    0 讨论(0)
提交回复
热议问题