问题描述
我正在使用CMake构建C ++项目,最近添加了使用Boost C ++库创建临时文件的功能。这就是我将Boost包含在CMake文件中的方式:
# get boost
SET(Boost_USE_STATIC_LIBS ON)
SET(Boost_USE_MULTITHREADED ON)
SET(Boost_USE_STATIC_RUNTIME OFF)
FIND_PACKAGE(Boost required COMPONENTS system filesystem)
INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR})
TARGET_LINK_LIBRARIES(${exe_name} ${Boost_LIBRARIES})
ADD_LIBRARY(${lib_name} ${common_SOURCES})
TARGET_LINK_LIBRARIES(${lib_name} ${CMAKE_DL_LIBS} ${Boost_LIBRARIES})
TARGET_LINK_LIBRARIES(${exe_name} ${lib_name})
这就是我在C ++中的称呼方式
#define BOOST_NO_CXX11_ScopED_ENUMS
#include <boost/filesystem.hpp>
#undef BOOST_NO_CXX11_ScopED_ENUMS
...
input_file *Utils::get_input_file_from_string(const std::string &inp) {
std::string real_inp(inp);
boost::filesystem::path temp_path = boost::filesystem::unique_path();
const std::string temp_pathstr = temp_path.native();
boost::filesystem::path temp_folder = boost::filesystem::temp_directory_path();
const std::string temp_folderstr = temp_folder.native();
const std::string temp_fname = temp_folderstr + "/" + temp_pathstr;
const char *temp_pathchar = temp_fname.c_str();
...
FILE *temp = fopen(temp_pathchar,"wb+");
...
input_file *ret = new input_file;
loadInput(ret,temp);
fclose(temp);
return ret;
}
运行程序时,出现以下错误:
terminate called after throwing an instance of 'std::runtime_error'
what(): locale::facet::_S_create_c_locale name not valid
Aborted (core dumped)
但是,通过运行bash命令...
unset LANG
...程序成功运行(注意echo $LANG
返回C.UTF-8
)
有没有一种方法可以编辑程序,这样就不必在每次加载新的shell实例时都运行unset LANG
命令?
编辑:我知道可以在c ++中取消设置环境变量,但是我相信Boost内必须存在与语言环境相关的解决方案,以确保不会引发错误。
(PS重申一下,在运行可执行文件之前调用unset LANG
时,程序会以所需的输出成功运行)
解决方法
如果没有来回操作或无法访问您的机器,很难调试良好,因为我无法在本地复制它。无论如何,我都会努力解决。我的猜测是由于.native()
转换为std::string
而引起的语言环境问题。尝试以下方法:
input_file *Utils::get_input_file_from_string(const std::string &inp) {
...
boost::filesystem::path temp_path = boost::filesystem::unique_path();
boost::filesystem::path temp_folder = boost::filesystem::temp_directory_path();
boost::filesystem::path temp_file_path = temp_folder / temp_path;
// try either:
std::string temp_file_path_string = temp_file_path.string();
const char *temp_pathchar = temp_file_path_string.c_str();
// or:
const char *temp_pathchar = temp_file_path.c_str();
...
}
如果使用正斜杠,如果在使用string()
的行中使用,这在非POSIX平台上将无法正常工作。
此外,我会尝试对显示的代码进行更多的最小化。 unique_path()
似乎引发了错误。尝试对路径或路径字符串进行硬编码,例如,查看错误是否仍然存在。