当你在Ubuntu 20.04上尝试安装ROS2 Galactic时,最令人沮丧的莫过于遇到"broken packages"错误。这个红色警告就像一堵墙,挡住了你探索机器人操作系统的道路。但别担心,这不是终点——aptitude命令可能就是你需要的那把钥匙。
在深入解决方案之前,我们先理解问题根源。ROS2 Galactic的依赖关系相当复杂,涉及数百个相互关联的软件包。当使用apt install时,它采用相对保守的依赖解析策略:
相比之下,aptitude采用更智能的依赖解析算法:
| 特性 | apt | aptitude |
|---|---|---|
| 依赖解析策略 | 保守型 | 启发式 |
| 解决方案数量 | 单一 | 多方案 |
| 版本灵活性 | 严格 | 可降级 |
| 交互界面 | 无 | 文本菜单 |
| 冲突处理 | 直接报错 | 提供解决方案 |
典型错误信息看起来像这样:
code复制The following packages have unmet dependencies:
ros-galactic-desktop : Depends: ros-galactic-action-tutorials-cpp but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
首先确保系统已更新并安装aptitude:
bash复制sudo apt update && sudo apt upgrade -y
sudo apt install aptitude -y
提示:如果遇到网络问题,建议先配置国内镜像源。Ubuntu 20.04的清华源配置如下:
bash复制sudo sed -i 's|http://.*archive.ubuntu.com|https://mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list
对于桌面完整版安装:
bash复制sudo aptitude install ros-galactic-desktop
对于最小化安装(仅基础功能):
bash复制sudo aptitude install ros-galactic-ros-base
执行后会进入aptitude的解决方案界面,你会看到类似这样的选项:
code复制The following actions will resolve these dependencies:
Keep the following packages at their current version:
1) libopenscenegraph161 [Not Installed]
2) libopenthreads20 [Not Installed]
3) ros-galactic-desktop [Not Installed]
Downgrade the following packages:
4) libcurl4 [7.68.0-1ubuntu2.7 (now) -> 7.68.0-1ubuntu2.5 (focal)]
Accept this solution? [Y/n/q/?]
关键操作指南:
n查看下一个解决方案(通常第一个不是最优解)Accept的解决方案Y执行在解决依赖冲突时,你会遇到几种典型方案:
保持当前版本(最保守但可能无法安装ROS2)
降级系统包(最常见有效方案)
libboost-*系列库的降级移除冲突包(激进但有效)
注意:选择降级方案时,建议记录被降级的包及其版本,便于后续恢复。
即使使用aptitude,某些特殊情况下仍可能遇到问题。以下是常见场景的应对策略:
当aptitude无法自动解决时,可以尝试手动指定版本:
bash复制sudo aptitude install ros-galactic-desktop libboost1.71=1.71.0-6ubuntu6
关键排查命令:
apt-cache depends ros-galactic-desktopapt-cache policy <package-name>dpkg -l | grep <package-prefix>如果你之前尝试过其他安装方法(如源码编译),可能需要清理残留:
bash复制sudo apt purge ~nros-galactic-*
sudo rm -rf /etc/ros/rosdep/
针对单个组件安装失败,可以尝试独立安装:
bash复制sudo aptitude install ros-galactic-rviz2 ros-galactic-turtlesim
成功安装后,还需要完成以下关键步骤:
将以下内容添加到~/.bashrc中:
bash复制source /opt/ros/galactic/setup.bash
echo "export RMW_IMPLEMENTATION=rmw_cyclonedds_cpp" >> ~/.bashrc
启动两个终端分别运行:
bash复制# 终端1 - 发布者
ros2 run demo_nodes_cpp talker
# 终端2 - 订阅者
ros2 run demo_nodes_py listener
预期输出:
code复制[INFO] [1623401499.188649472] [talker]: Publishing: 'Hello World: 1'
[INFO] [1623401519.208580911] [listener]: I heard: [Hello World: 21]
为后续开发准备工作区:
bash复制mkdir -p ~/ros2_ws/src
cd ~/ros2_ws
colcon build
ROS2安装后,为保持系统稳定:
谨慎执行系统升级:
bash复制sudo apt-mark hold ros-galactic-* libboost1.71*
定期更新ROS2包:
bash复制sudo aptitude update
sudo aptitude safe-upgrade
备份关键配置:
bash复制dpkg --get-selections | grep ros-galactic > ros2_packages.list
恢复原系统状态(如需卸载):
bash复制sudo aptitude purge ~nros-galactic-*
sudo aptitude install libboost1.71=1.71.0-6ubuntu6
遇到特别棘手的问题时,ROS社区提供了丰富的资源: