I've read a lot of posts and yet I don't understand how to create a simple dynamic library on windows using MSVC in command line. What I'm doing is:
1º) Code the DLL
dynamic.h
#pragma once
__declspec(dllexport) void HelloWorld();
dynamic.c
#include "dynamic.h"
#include <stdio.h>
void HelloWorld(){
printf("Hello World");
}
2º) Compile it
cl /LD dynamic.c
(it compiles correctly and without errors generating dynamic.dll and dynamic.lib)
3º) Try to test it
main.c
#include<stdio.h>
#include"dynamic.h"
int main(){
HelloWorld();
return 0;
}
cl main.c dynamic.lib
ERROR (by cl.exe x64)
main.cpp
Microsoft (R) Incremental Linker Version 14.16.27034.0
Copyright (C) Microsoft Corporation. All rights reserved.
/out:main.exe
main.obj
.\dynamic.lib
main.obj : error LNK2019: unresolved external symbol "void __cdecl HelloWorld(void)" (?HelloWorld@@YAXXZ) referred in main
main.exe : fatal error LNK1120: unresolved externals
Please teach me how dynamic libraries compilation really work because I can't understand
Try this way in dynamic.h :
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) void HelloWorld();
#ifdef __cplusplus
}
#endif
Use 'dumpbin.exe /exports dynamic.dll' to show exported symbols
In main.c
it needs to see the function declaration like this:
__declspec(dllimport) void HelloWorld();
So you cannot use the same dynamic.h
as you currently have, for both building the DLL and building main.c
.
Normally people will use a preprocessor setup so the same header file has a different declspec depending who is including it, for example:
// dynamic.h
#ifndef DLL_FUNCTION
#define DLL_FUNCTION __declspec(dllimport)
#endif
DLL_FUNCTION void HelloWorld();
dynamic.c (in the DLL):
#define DLL_FUNCTION __declspec(dllexport)
#include "dynamic.h"
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.