简体   繁体   中英

How to correctly link a dll project to another project in the same C++ solution in Visual Studio?

I have a solution with two C++ projects:

  • Project A: Builds a dll
  • Project B: An executable project that uses the dll from Project A.

What is the correct way to make the dll from project A accessible by Project B? Right now what I do is:

  • Set Build order as Project A -> Project B
  • Add the source of Project A to the include directory list of Project B.
  • Add a pre-build event in Project B to copy the dll to Project B's output directory.

I was wondering if there was a more standard way of doing this. I searched and some other answers suggest adding a project reference, but that doesn't seem to copy the dll, so I'm not really sure what it's supposed to do.

Also, what do I do with the lib file that is generated along with the dll when building project A?

I am using Visual Studio 2017 by the way.

If the DLL is going to be used only by the current solution the the "Add reference" method is fine, the output directories of all projects should already be the same (likely $(SolutionDir)\\$(Platform)\\$(Configuration)) while the intermediate directories will differ (likely $(Platform)\\$(Configuration)), so no copying will be needed. The "Add reference" method causes the dependant project to bring in the .lib with no further work needed on your part.

If the DLL is going to be used in multiple solutions I suggest altering the standard __declspec(dllexport|dllimport) block to include a #pragma comment(lib, ...) directive:

#if defined(MYLIB_EXPORTS)
#define MYLIB_API __declspec(dllexport)
#else
#define MYLIB_API __declspec(dllimport)
#pragma comment(lib, '"mylib.lib")
#endif

That way simply including the library header will have the linker bring in the needed .lib file. I do have a directory structure like the following:

<root>
\projects
\projects\shared
\projects\shared\bin
\projects\shared\bin64
\projects\shared\include
\projects\shared\lib
\projects\shared\lib64

and scripts I run under WSL that takes VS output and copies files into the appropriate directories. This way any projects I create that are intended for future use do not require that I add project-specific paths to the compiler search paths, I simply need to alter the global property sheets to look under \\project\\shared at appropriate times (and the windows environment to include \\project\\shared\\bin64;\\project\\shared\\bin)

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