【问题标题】:what must I link to avoid linker error on _aligned_alloc (MSVC command-line)?我必须链接什么以避免 _aligned_alloc(MSVC 命令行)上的链接器错误?
【发布时间】:2021-06-02 16:24:35
【问题描述】:

我正在尝试使用 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 开关都是大量谷歌搜索的结果,似乎他们应该这样做,除非这些分配函数不在任何这些标准库中......但在那种情况下,我不知道他们可能在哪里。

谁能告诉我我需要包含什么库来解析这些符号,或者我可能做错了什么?

【问题讨论】:

标签: visual-c++ linker malloc cl


【解决方案1】:

根据[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

【讨论】:

  • 这是一个非常完整和有用的答案,让我不解。谢谢!
猜你喜欢
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 2014-03-26
  • 2019-08-14
  • 1970-01-01
  • 1970-01-01
  • 2011-07-22
  • 1970-01-01
相关资源
最近更新 更多