gpt4 book ai didi

使用 MSVC 命令行创建动态库

转载 作者:行者123 更新时间:2023-12-02 16:46:36 27 4
gpt4 key购买 nike

我已经阅读了很多帖子,但我不明白如何在命令行中使用 MSVC 在 Windows 上创建一个简单的动态库。我正在做的是:

1º) 编写 DLL 代码

动态.h

#pragma once

__declspec(dllexport) void HelloWorld();

动态.c

#include "dynamic.h"
#include <stdio.h>

void HelloWorld(){
printf("Hello World");
}

2º) 编译

cl /LD dynamic.c

(它编译正确并且没有错误生成 dynamic.dll 和 dynamic.lib)

3º) 尝试测试一下

ma​​in.c

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

HelloWorld();

return 0;
}
cl main.c dynamic.lib

错误(来自 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

请教我动态库编译是如何工作的,因为我看不懂

最佳答案

main.c 中,需要看到这样的函数声明:

__declspec(dllimport) void HelloWorld();

因此您不能使用与当前相同的 dynamic.h 来构建 DLL 和构建 main.c

通常人们会使用预处理器设置,因此相同的头文件具有不同的 declspec,具体取决于包含它的人,例如:

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

DLL_FUNCTION void HelloWorld();

dynamic.c(在 DLL 中):

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

关于使用 MSVC 命令行创建动态库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60288522/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com