开发者

extern(al) problem

开发者 https://www.devze.com 2022-12-29 20:09 出处:网络
Why can\'t I compile this code? //main #include \"stdafx.h\" #include \"X.h\" #include \"Y.h\" //#include \"def.h\"

Why can't I compile this code?

   //main
    #include "stdafx.h"
    #include "X.h"
    #include "Y.h"
    //#include "def.h"

    extern X operator*(X, Y);//HERE ARE DECLARED EXTERNAL *(X,Y) AND f(X)
    extern int f(X);
    /*GLOBALS*/
    X x = 1;
    Y y = x;
    int i = 2;

    int _tmain(int argc, _TCHAR* argv[])
    {
        i + 10; 
        y + 10;
        y + 10 * y;
        //x + (y + i);
        x * x + i;
        f(7);
        //f(y);
        //y + y;
        //106 + y;
        return 0;

    }

//X
struct X
{
    int i;
    X(int value):i(value)
    {
    }
    X operator+(int value)
    {
        return X(i + value);
    }
    operator int()
    {
        return i;
    }
};
//Y
struct Y
{
    int i;
    Y(X x):i(x.i)
    {   }
    Y operator+(X x)
    {
        return Y(i + x.i);
    }
};

//def.h
int f(X x);
X operator*(X x, Y y);
//def.cpp
#include "stdafx.h"
#include "def.h"
#include "X.h"
#include "Y.h"


int f(X x)
{
    return x;
}

X operator*(X x, Y y)
{
    return x * y;
}

I'm getting err msg:

Error 2 error LNK2019: unresolved external symbol "int __cdecl f(struct X)"

Error 3 error LNK2019: unresolved external symbol "struct X __cdecl operator*(struct X,struct Y)"

Another interesting thing is that开发者_如何学Python if I place the implementation in def.h file it does compiles without errs. But then what about def.cpp? Why I'm not getting err msg that function f(X) is already defined? Here shouldn't apply ODR rule. Second concern I'm having is that if in def.cpp I change the return type of f from int to double intelliSense underlines this as an error but program still compiles? Why?


Just remove the word extern. It's the default anyway -- it doesn't mean anything for function declarations, and it should be avoided in any case in C++. if you're still having issues it's likely def.cpp is not being compiled into your program.


It looks like def.cpp is not being used here. As you point out, if def.cpp was being compiled, it includes def.h, and if the functions were defined in def.h, that would be a multiple function definition warning or error.

Check your project settings.

0

精彩评论

暂无评论...
验证码 换一张
取 消