我有一个ResourceManager
类,我在这里尝试将其用作单例。我在下面列出了文件resources.hpp
和resources.cpp
。最后的代码清单是ResourceManager::instance()
的用法和下面的错误消息。我尝试了很多诸如前向声明等操作,但是找不到让编译器成功的方法。
resources.hpp
namespace X11 {
class ResourceManager {
private:
static ResourceManager* _instance;
ResourceManager() {
//logic
};
ResourceManager (const ResourceManager&);
~ResourceManager() = default;
public:
static ResourceManager* instance();
std::vector<sf::Font> fonts;
};
}
resources.cpp
#include "resources.hpp"
namespace X11 {
ResourceManager* ResourceManager::_instance = 0;
ResourceManager* ResourceManager::instance() {
if (!ResourceManager::_instance)
ResourceManager::_instance = new ResourceManager();
return ResourceManager::_instance;
}
}
用法(initialized.cpp)
#include "initializer.hpp"
// initializer.hpp includes "resources.hpp"
void Initializer::init_right_bar(Menu& menu) {
// logic
text.setFont(ResourceManager::instance()->fonts[0]);
// logic
}
错误消息
[ 30%] Building CXX object CMakeFiles/vilsoc.dir/src/initializer.cpp.o
[ 40%] Building CXX object CMakeFiles/vilsoc.dir/src/vilsoc.cpp.o
[ 50%] Linking CXX executable vilsoc
/usr/bin/ld: CMakeFiles/vilsoc.dir/src/initializer.cpp.o: in function `X11::Initializer::init_right_bar(X11::Menu&)':
initializer.cpp:(.text+0x1715): undefined reference to `X11::ResourceManager::instance()'
collect2: error: ld returned 1 exit status
已解决 这些评论得出的结论是,我不是通过CMake更新我的makefile,因此链接器找不到源文件。