如何解决我必须链接什么才能避免 _aligned_allocMSVC 命令行上的链接器错误?
我正在尝试使用 cl 命令行工具在 Windows 上构建一个包含 _aligned_alloc、_aligned_realloc 和 _aligned_free 的简单 DLL。我的源文件是一个 .c 文件,包括
cl /LD CustomAllocators.c /NODEFAULTLIB:libcmt.lib /NODEFAULTLIB:libcmtd.lib /NODEFAULTLIB:msvcrtd.lib
CustomAllocators.obj : error LNK2019: unresolved external symbol _aligned_alloc referenced in function Allocate
CustomAllocators.dll : Fatal error LNK1120: 1 unresolved externals
所有这些 /NODEFAULTLIB 开关都是谷歌搜索的结果,看起来他们应该这样做,除非这些分配函数不在任何标准库中......但在这种情况下,我不知道他们可能在哪里。
谁能告诉我我需要包含什么库来解析这些符号,或者我可能做错了什么?
解决方法
根据[MS.Docs]: <cstdlib> - Remarks(重点是我的):
这些函数具有 C 标准库中指定的语义。 MSVC 不支持 aligned_alloc
函数。
您可能想切换到 [MS.Docs]: _aligned_malloc。
dll00.c:
#include <stdio.h>
#include <stdlib.h>
#if defined(_WIN32)
# define DLL00_EXPORT_API __declspec(dllexport)
#else
# define DLL00_EXPORT_API
#endif
#if defined(__cplusplus)
extern "C" {
#endif
DLL00_EXPORT_API int dll00Func00();
#if defined(__cplusplus)
}
#endif
int dll00Func00() {
void *p = _aligned_malloc(2048,1024);
printf("Aligned pointer: %p\n",p);
_aligned_free(p);
return 0;
}
输出(构建 - 检查 [MS.Docs]: Use the Microsoft C++ toolset from the command line):
[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q067809018]> sopr.bat
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###
[prompt]> "c:\Install\pc032\Microsoft\VisualStudioCommunity\2019\VC\Auxiliary\Build\vcvarsall.bat" x64
**********************************************************************
** Visual Studio 2019 Developer Command Prompt v16.10.0
** Copyright (c) 2021 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'
[prompt]> dir /b
dll00.c
[prompt]>
[prompt]> cl /nologo /MD /DDLL dll00.c /link /NOLOGO /DLL /OUT:dll00.dll
dll00.c
Creating library dll00.lib and object dll00.exp
[prompt]> dir /b
dll00.c
dll00.dll
dll00.exp
dll00.lib
dll00.obj
[prompt]>
测试 .dll:
[prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.08.07_test0\Scripts\python.exe"
Python 3.8.7 (tags/v3.8.7:6503f05,Dec 21 2020,17:59:51) [MSC v.1928 64 bit (AMD64)] on win32
Type "help","copyright","credits" or "license" for more information.
>>>
>>> import ctypes as ct
>>>
>>> dll = ct.CDLL("./dll00.dll")
>>> # This is for display purpose only. Skipping crucial steps. Don't do this in production!!!
>>> dll.dll00Func00()
Aligned pointer: 0000025E33A9A000
0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。