我尝试使用 Cmake 从本质上构建 PhysFS 库,我使用的是 Code::Blocks mingw makefile。我可以在我的项目中导入,我可以在技术上声明 PhysFS_init() 函数(尽管这给我的参数太少错误)但是当我添加一个参数时它告诉我 PHYSFS_init 是一个 undefined reference 。
这对我来说听起来很傻,当它没有参数时你怎么能认出它,但是当我添加参数时假装它不存在?我已经运行 CMake 两次,但我只是得到了这个:
[...]\src\main.cpp|20|undefined reference to `PHYSFS_init'|
代码,如有必要(就一点,其余的无关紧要):
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include <iostream>
#include "Globals.h"
#include "GameStates.h"
#include "GameWindow.h"
#include "GameMenu.h"
#include <physfs.h>
int main(int argc, char** argv)
{
///<|===================| Classes & Declarations |===================|>
sf::Event ev;
sf::RenderWindow winMain ( sf::VideoMode( WindowWidth, WindowHeight, 32 ), WindowTitle );
sf::Image Icon;
GameStates gameState;
GameMenu TitleMenu;
MenuButton buttons[4];
PHYSFS_init(NULL);
为什么会这样?我需要做什么才能在我的项目中使用 PhysFS?我用 CMake 构建了库,包含了我需要的库,然后我尝试初始化 PhysFS,这给了我一个错误,这让我觉得 C++ 编译程序的方式很愚蠢。
最佳答案
这是对 C++ 库如何工作的一般解释:
PHYSFS 可能由头文件和静态/动态库组成。头文件是声明库的所有函数/类的地方,但没有定义。因此,当您将头文件包含到您的项目中时,您的编译器现在可以知道您在库中调用的函数存在,以及它们采用什么类型的参数等等。
所以要使用一个库,你必须包含它的头文件,这意味着你必须将它的include目录添加到project/cmakelists.txt。
#some similar path to this
include_directories( /path/to/PHYSFS/include)
现在,当您实际将可执行文件链接到二进制文件时,必须“解析”这些函数,以便链接器知道它们的实际位置,以便可以调用它们。这称为与库的“链接”。
所以要使用一个库,你必须链接它的库文件。
在 cmake 中,这是按如下方式完成的:
add_executable(myexe myexe.cpp)
#Add library directory paths here
link_directories( /path/to/PHYSFSlibs/)
#libPHYS.a or libPHYS.so if using gcc convention, libPHYS.lib if MSVC convention
#cmake allows us to use the name of the library, instead of the filename to be portable.
target_link_libraries(myexe PHYSFS)
我对 PHYSFS 不是特别熟悉,但是如果您将它编译为一个库,您应该有这些文件之一可以链接到。
undefined reference to `PHYSFS_init
这是“链接”的问题,通常意味着您链接库失败,或者库缺少此功能的实现。链接库应该可以解决这个问题。
编辑
我误读了您的问题,并假设您在项目中使用 cmake 并链接到 PHYSFS。
首先,您必须单独构建 PHYSFS,它将根据平台/IDE 生成库文件(.a、.so 或 .lib),然后您必须在 C::B 链接器选项中链接该库文件。
为此:
转到项目->构建选项。单击链接器设置。
图片(来自 here ):
添加库。
关于c++ - 运行 cmake 后出现 undefined reference 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12645117/