0

I'm trying to create a .dll and .lib files with VS2019 using this guide and load my library statically and dynamically.
I have dll project named dllSolution.
In my dllSolution there are standart framework.h, pch.h, dllmain.cpp, pch.cpp and my a.h file:

#pragma once

#ifdef DLLSOLUTION_EXPORTS
#define DLLSOLUTION_API __declspec(dllexport)
#else
#define DLLSOLUTION_API __declspec(dllimport)
#endif  // !DLLSOLUTION_EXPORTS

#ifndef WINAPI
#define WINAPI __stdcall
#endif  // !WINAPI

extern "C" DLLSOLUTION_API int WINAPI a();

with a.cpp:

#include "a.h"
#include "pch.h"

#ifndef WINAPI
#define WINAPI __stdcall
#endif  // !WINAPI

int WINAPI a() { return 10; }

but when I build this project it produces no .lib file as if there is no export from library:

1>------ Rebuild All started: Project: dllSolution, Configuration: Debug Win32 ------
1>pch.cpp
1>a.cpp
1>dllmain.cpp
1>Generating Code...
1>dllSolution.vcxproj -> C:\CoolPathToMyDll\dllSolution\Debug\dllSolution.dll
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

I have tried to move implementation into dllmain.cpp with no result.
I also have tried to switch ConfigurationType to StaticLibrary(.lib) and fine, it generates .lib, but then, when I statically link my library to another project and use this a() in my main(), it says:

error LNK2019: unresolved external symbol __imp__a@0 referenced in function _main

What is the problem and why does this problem happen?

Community
  • 1
  • 1
KainWhite
  • 101
  • 2
  • 8
  • The #include for pch.h must be first. As-is it skips the #include for a.h (note the warning you got for that), so the compiler doesn't know you tried to export it. – Hans Passant Nov 28 '19 at 13:42
  • @HansPassant, thanks, placing pch.h at the top of includes solved the problem. Can you give a bit more explanation of the situation(why does including pch skips includes before? any documantation for that?)? Btw, I didn't get any any warnings for including a.h before pch.h. – KainWhite Nov 28 '19 at 14:45
  • https://learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-1-c4627?view=vs-2019 It is supposed to be elevated to a fatal C1010 error in VS2017 and up, VS2019 has too many agile bugs to be sure. – Hans Passant Nov 28 '19 at 14:58

1 Answers1

0

As @HansPassant admitted, the problem is

The #include for pch.h must be first. As-is it skips the #include for a.h (note the warning you got for that), so the compiler doesn't know you tried to export it.

Placing any includes before pch.h results in warning in VS2017, but not in VS2019 (at the time of asking the question).

Reason of this behavior is explained here (short version) and here (long version).

Hope this answer will help someone to save hours of useless changing linking options.

KainWhite
  • 101
  • 2
  • 8