0

File F1.h is

enum class E { A, B, C };

template<class E> class X {
public:   X(const E& y) { self.z = y; }
};

__declspec(dllexport) X<E> foo; // Attempt to declare but not instantiate

File F1.cpp is

#include <F1.h>
__declspec(dllexport) X<E> foo(E.A); // Attempt to instantiate matching .H declaration

File F2.cpp is

#include <F1.h>

void f()
{
  E z = foo.z; // Attempt to use from declaration without instantiating
}

A Visual Studio C++ project P has F1.cpp and F2.cpp. Building this project gives LNK2005 error that foo in F1.obj is already defined in F2.obj.

Is there a way to set this up so that foo is exported in P.DLL from F1.obj and is available in F2.cpp and is not defined in F2.obj?

Lars Ericson
  • 1,952
  • 4
  • 32
  • 45
  • What is "self.z = y; " means? There is no self in c++, do you mean "this"? – Severin Pappadeux Sep 01 '23 at 00:12
  • And if we're talking `this`, consider using the Member Initializer List to initialize the member instead of in-body assignment of the member. – user4581301 Sep 01 '23 at 00:18
  • I think you may be looking for [the `extern` keyword](https://stackoverflow.com/questions/10422034/when-to-use-extern-in-c), but my Windows is shaky so I'm not sure on what extra syntax might be needed with a DLL. – user4581301 Sep 01 '23 at 00:21
  • @user4581301 Yeah, adding `extern` to the declaration in the header should do the trick, along with having the standard 'conditional' definitions for importing/exporting the DLLs stuffs. – Adrian Mole Sep 01 '23 at 03:25

1 Answers1

0

There are variables undefined in your example.

Here is a sample:

F1.h

#pragma once

#ifdef MYDLL_EXPORTS
#define MYDLL_API __declspec(dllexport)
#else
#define MYDLL_API __declspec(dllimport)
#endif


enum class E { A, B, C };

template<class E> 
class X 
{
public:  
    X(const E& y) { this->Z = y; }
    E Z;
};

extern  MYDLL_API X<E> foo;
 MYDLL_API void f();

F1.cpp

#include "F1.h"
X<E> foo(E::B);

F2.cpp

#include<iostream>
#include "F1.h"

void f()
{
    E z = foo.Z;
    std::cout << (int)z;
}

And test project main.cpp

#include <iostream>
#include"../F1.h"    

int main()
{
    std::cout <<(int) foo.Z<<std::endl;
    f();
}

OutPut

1
1
Minxin Yu - MSFT
  • 2,234
  • 1
  • 3
  • 14