Undefined Reference to non-member operators from dll

Viewed 94

For an assignment I created a fractions class that overloads many operators. I then converted it into a dll to be used by another program. The issue I am having is that when I try to use the non-member operators I get the error "undefined reference to 'operator+'".

I believe I have implemented the dll correctly as the constructors works correctly as do any member functions/operators. Just the non-member operators are giving me this issue.

        Fraction frac1(1,5); //No errors
        Fraction frac2(2,5); //No errors
        Fraction frac3 = frac2 + frac1; //ERROR: undefined reference to 'operator+'
        //Note: + operator is a non-member operator
        frac2 += frac1; //No errors and is a member operator

I've been trying to solve this and googling for hours with no success. It could possible be a linking issue but I have had no luck figuring that out if so.

I'm using Qt Creator (since I am implenting a GUI) and MinGW.

1 Answers

Short version: you need to properly export/import our library objects and code.


Long Version:

Somewhere in your header will be a macro definition similar to the following:

#ifdef MYDLL_EXPORTS
#define MYDLL_API __declspec(export)
#else
#define MYDLL_API __declspec(import)
#endif

This macro is later used in a variety of places in the header, and implementation files. For example, a simple function is declared like this:

MYDLL_API int MyFunction(int);

or as another example, an entire class and its members likewise can be exported:

class MYDLL_API MyClass
{
    // members...
};

When compiling your DLL (i.e building the actual DLL project), a preprocessor macro, MYDLL_EXPORTS, is defined either in a primary project-only header (NOT the dll expose' header) or on the actual build command. This, in turn, makes all MYDLL_API decorated symbols "exported". I.e., using our API example above, this:

MYDLL_API int MyFunction(int);

becomes this:

__declspec(dllexport) int MyFunction(int);

When consuming the header and DLL import library, do NOT define the MYDLL_EXPORTS macro, and in turn the same function decl in the header now looks like this:

__declspec(dllimport) int MyFunction(int);

Ok. That's a lot of information or what ultimately comes down to this. You have a free-function operator that is declared, but not exported, in your DLL. I.e. given all of the above, you have a class Fraction that probably looks like this:

class MYDLL_API Fraction
{
    // members
};

and also a free-function operator that looks like this:

Fraction operator +(Fraction, Fraction);

The latter should look like this:

MYDLL_API Fraction operator +(Fraction, Fraction) 
Related