简体   繁体   中英

how to share class between c++ projects?

My VS2012 Solution contains several VC++ projects. I also have many common files that need to be shared. It's easy to share enum's and structures. I just "include" corresponding header file and that's it. I even don't need to compile my "commons" project!

But what if I need to share more complex classes that contain both .h and .cpp files, and so need to be compiled?

And the most complicated question - can I share thread-safe singleton? I want to access it from different projects from different threads (but from one process).

I guess I should use something like static or dynamic linking, but i'm not sure. Probably someone can link step-by-step tutorial to solve such problem?

I would prefer something portable as I will move entire solution to Linux later.

The projects that contain classes that you want to share should export their symbols. When you create a DLL project in Visual Studio you can give it the option to "Export" symbols and it provides some boiler-plate code for you to use.

In essence, in your libraries header file, it will give you:

// myapi.h

#if defined(MYAPIEXPORTS)
    #define MYAPI __declspec(dllexport)
#else
    #define MYAPI __declspec(dllimport)
#endif

'MYAPIEXPORTS' is provided by the wizard, but it's a compiler preprocessor directive ONLY on the library itself. Hence when you compile the library, MYAPI is for exporting and when the header file is included in your other projects, it will be for importing.

Now let's look at a class you want to share.

// myclass.h

class MYAPI MyClass
{
public:
    MyClass();
    ~MyClass();
};


// myclass.cpp
#include "myClass.h"

MyClass::MyClass() { /* ... */ };
MyClass::~MyClass() { /* .... */ }

Your other projects then need to link with the resulting .lib file that is generated.

Note that if you have a template<> class contained entirely within a header file, you do not export it. That will behave like your enums and typedefs.

To answer the second part of your question, yes a singleton defined in your library will be accessible to the main project also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM