简体   繁体   English

使用 MSVC 命令行创建动态库

[英]Create dynamic library using MSVC command line

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.我已经阅读了很多帖子,但我不明白如何在命令行中使用 MSVC 在 Windows 上创建一个简单的动态库。 What I'm doing is:我正在做的是:

1º) Code the DLL 1º) 对 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 2º) 编译它

cl /LD dynamic.c

(it compiles correctly and without errors generating dynamic.dll and dynamic.lib) (它正确编译并且没有错误生成 dynamic.dll 和 dynamic.lib)

3º) Try to test it 3º) 尝试测试一下

main.c主文件

#include<stdio.h>
#include"dynamic.h"
int main(){

    HelloWorld();

    return 0;
}
cl main.c dynamic.lib

ERROR (by cl.exe x64)错误(通过 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 :在 dynamic.h 中尝试这种方式:

#ifdef __cplusplus  
extern "C" {
#endif 
    __declspec(dllexport) void HelloWorld();
#ifdef __cplusplus 
}
#endif 

Use 'dumpbin.exe /exports dynamic.dll' to show exported symbols使用 'dumpbin.exe /exports dynamic.dll' 显示导出的符号

In main.c it needs to see the function declaration like this:main.c它需要看到这样的函数声明:

__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 .因此,您不能使用与当前相同的dynamic.h来构建 DLL 和构建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:通常人们会使用预处理器设置,因此相同的头文件具有不同的 declspec,具体取决于包含它的人,例如:

// dynamic.h
#ifndef DLL_FUNCTION 
#define DLL_FUNCTION __declspec(dllimport)
#endif

DLL_FUNCTION void HelloWorld();

dynamic.c (in the DLL): dynamic.c(在 DLL 中):

#define DLL_FUNCTION __declspec(dllexport)
#include "dynamic.h"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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