You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ROS节点使用std::filesystem编译链接报错问题求助

问题原因与解决方法

第一阶段报错:找不到std::filesystem命名空间

该报错是由于ROS Noetic默认使用C14标准编译,而std::filesystem是C17才正式纳入标准库的特性。Ubuntu 20.04自带的GCC 9版本支持C17标准,优先选择开启C17编译解决问题,操作如下:

1. 修改CMakeLists.txt

在cmake_minimum_required行之后、project行之前添加编译标准配置:

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

原有节点编译和链接配置无需额外修改:

add_executable (node src/node.cpp)
target_link_libraries(node
    ${catkin_LIBRARIES}
)

2. 修正node.cpp代码

补充缺失的命名空间别名定义,补全STL类的std::前缀,修复语法错误:

#include <ros/ros.h>
#include <fstream>
#include <string>
#include <iostream>
#include <filesystem>
#include <set>

// 补充命名空间别名
namespace fs = std::filesystem;

int main(int argc, char **argv)
{
    // 补全std::前缀
    std::string path_name = "/bin";
    std::set<fs::path> sorted_by_name;

    for (auto &entry : fs::directory_iterator(path_name))
    {
        sorted_by_name.insert(entry.path()); // 补充分号
    }
    
    return 0;
}

第二阶段报错:std::experimental::filesystem相关未定义引用

如果无法升级到C17标准,使用C14下的实验版filesystem时出现该报错,是因为没有链接对应的实验库,修改方法如下:

1. 修改CMakeLists.txt

无需修改编译标准,仅在node节点的链接库中添加stdc++fs:

add_executable (node src/node.cpp)
target_link_libraries(node
    ${catkin_LIBRARIES}
    stdc++fs
)

2. 修正node.cpp代码

头文件和命名空间替换为实验版:

#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;

内容的提问来源于stack exchange,提问作者rebubi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 09:57:03