如何在Visual Studio中静态链接FreeType2

How to statically link FreeType2 in Visual Studio?

本文关键字:静态 链接 FreeType2 Studio Visual      更新时间:2023-10-16

我通过选择调试多线程/单线程配置,将 Freetype 2.9 从 VS2017 中的源代码构建到静态库中。看起来,静态库被放置在freetype-2.9\objs\x64\Debug Static\freetype.lib中。

在VS2017中,在其他库目录中,我添加了freetype-2.9\objs\x64\Debug Static。在 Other Dependencies 中,我添加了 freetype.lib。并将运行时库设置为 MTd。但是,编译会引发链接器错误:

1>------ Build started: Project: HelloFreetype, Configuration: Debug x64 ------
1>Source.cpp
1>Source.obj : error LNK2019: unresolved external symbol __imp_FT_Init_FreeType referenced in function main
1>Source.obj : error LNK2019: unresolved external symbol __imp_FT_Done_FreeType referenced in function main
1>C:UsersjoaqoDocumentsHelloFreetypex64DebugHelloFreetype.exe : fatal error LNK1120: 2 unresolved externals
1>Done building project "HelloFreetype.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Freetype 对预处理器有不寻常的用途,所以这里也是代码:

#include <ft2build.h>
#include FT_FREETYPE_H
int main(int argc, char **argv)
{
    FT_Library  library;
    int error = FT_Init_FreeType(&library);
    if (error) {
        printf("FreeType: Initilization errorn");
        exit(EXIT_FAILURE);
    }
    FT_Done_FreeType(library);
    exit(EXIT_SUCCESS);
}

x86 平台、发布配置和/或将 Windows SDK 重定向到 8.1 也会发生同样的错误(Freetype 也是使用 SDK 8.1 构建的(。也尝试过Freetype 2.7.1但没有成功。尝试链接到动态库完全没有问题!

感谢您的任何帮助!

> 我按照步骤重现了相同的链接器错误,但使用 VS2013。在构建 FreeType 时,我注意到几个 C4273 编译器警告,如下所示:

1>......srcbaseftinit.c(321): warning C4273: 'FT_Init_FreeType' : inconsistent dll linkage
1>          C:librariesfreetype-2.9includefreetype/freetype.h(1987) : see previous definition of 'FT_Init_FreeType'

为了解决这些编译器警告,我编辑了config/ftconfig.h FreeType 头文件。我更改了以下行,

#define FT_EXPORT( x )  __declspec( dllimport )  x

#define FT_EXPORT( x ) extern x

然后重建了自由类型。这些更改后,链接器错误不再发生。

我相信

FreeType 2.9 中这个问题的原因是由于 ftconfig.h 中FT_EXPORT定义的更改。

// From ftconfig.h - FreeType 2.9
#ifndef FT_EXPORT
    #ifdef __cplusplus
    #define FT_EXPORT( x )  extern "C"  x
    #else
    #define FT_EXPORT( x )  extern  x
    #endif
    #ifdef _MSC_VER
        #undef FT_EXPORT
        #ifdef _DLL
        #define FT_EXPORT( x )  __declspec( dllexport )  x
        #else
        #define FT_EXPORT( x )  __declspec( dllimport )  x
        #endif
    #endif
#endif /* !FT_EXPORT */

请注意_MSC_VER部分将如何撤消前面的定义。此_MSC_VER块在早期版本的 FreeType 中不存在。

如果你只想构建一个静态库(没有DLL(,那么删除_MSC_VER部分,如下所示:

#ifndef FT_EXPORT
    #ifdef __cplusplus
    #define FT_EXPORT( x )  extern "C"  x
    #else
    #define FT_EXPORT( x )  extern  x
    #endif
#endif /* !FT_EXPORT */