c++ - 为什么此代码会导致分段错误错误?
问题描述
我正在使用 cmake 构建它,在 ubuntu 19.04 上使用 gcc 当我运行它时,它会导致 list_dir 函数内部出现分段错误异常。我不知道为什么。请帮忙。任何帮助将不胜感激。
#include <string>
#include <iostream>
#include <vector>
#include <filesystem>
namespace fs = std::filesystem;
static void list_dir(const std::string &path, bool recursive){
try{
std::vector<std::string> dirs;
try{
for (const auto &entry : fs::directory_iterator(path)){
std::cout << entry << "\n";
if(recursive && entry.is_directory() && !entry.is_symlink())
dirs.push_back(entry.path().string());
}
}
catch(const fs::filesystem_error &err){
std::cerr << "err: " << err.what() << "\n";
}
if(recursive){
for (const auto &p : dirs)
list_dir(p, true);
}
}
catch(const std::exception &err){
std::cerr << "err: " << err.what() << "\n";
}
}
int main (int argc, char *argv[]) {
if (argc != 2)
{
std::cerr << "Usage: index <dir>\n";
return 1;
}
list_dir(argv[1], true);
std::cout << "Done.\n";
return 0;
}
更新:异常发生在这行代码上
for (const auto &entry : fs::directory_iterator(path))
更新:如果有人感兴趣,这里是 cmake 文件
cmake_minimum_required(VERSION 3.1)
set(CMAKE_C_COMPILER "gcc")
set(CMAKE_CXX_COMPILER "g++")
project(index VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
file(GLOB_RECURSE SourceFiles "src/*.cpp" "src/*.h")
add_executable(${PROJECT_NAME} ${SourceFiles})
解决方案
I just solved the problem, I didn't link against the filesystem library, which was causing the error, although I have no idea why the code can still be compiled without the proper linking libraries...
In cmake, after I added:
target_link_libraries(${PROJECT_NAME} "-lstdc++fs")
Everything works fine now.
推荐阅读
- r - R读取缺少的Stata
- freemarker - 如何在 Freemarker 中将金额转换为单词格式?
- java - 如何多次调用 SwingWorker?
- powershell - 数组未正确加载
- python - Binance python websocket - 没有响应
- javascript - Typescript 中的错误导入
- facebook - 为什么即使我已登录 Facebook 且未调用 FB.logout(),FB.getLoginStatus() 仍会返回响应状态“未知”?
- javascript - 如何在 React 功能组件中拥有不变的变量副本?
- python - 硒“FirefoxWebElement”对象不可迭代
- xpath - 仅当“/a/@href”存在时,如何通过“/a”的 IMPORTXML 文本值导入?