error while loading shared libraries
当出现 **"error while loading shared libraries"** 且确认是因为 **未正确加载环境变量**(特别是 `LD_LIBRARY_PATH`)时,根本原因确实是修改环境变量后**未执行 `source` 命令**,导致新配置未生效。以下是详细解释和解决方法:
---
### 为什么需要 `source`?
1. **环境变量的工作原理**
当您在终端中执行 `export LD_LIBRARY_PATH=/new/path:$LD_LIBRARY_PATH` 时:
- 该命令只会修改 **当前 Shell 进程** 的环境变量
- **配置文件(如 `~/.bashrc`)中的设置不会自动加载到已打开的终端**
2. **`source` 的作用**
- `source 文件名` 或 `. 文件名` 命令会让当前 Shell **立即执行**指定文件中的所有命令
- 相当于让配置文件中的设置**在当前终端会话中生效**
---
### 典型错误场景演示
假设您在 `~/.bashrc` 中添加了库路径:
```bash
# ~/.bashrc 末尾添加
export LD_LIBRARY_PATH="/opt/custom/libs:$LD_LIBRARY_PATH"
```
#### ❌ 错误操作:
1. 编辑保存 `~/.bashrc` 后直接运行程序:
```bash
./my_app
# 报错: error while loading shared libraries: libxxx.so: cannot open...
```
**原因**:当前终端会话仍在使用旧的 `LD_LIBRARY_PATH`(不包含 `/opt/custom/libs`)
#### ✅ 正确操作:
```bash
# 1. 编辑配置文件后执行:
source ~/.bashrc # 或简写为: . ~/.bashrc
# 2. 验证变量是否更新:
echo $LD_LIBRARY_PATH
# 应显示包含 /opt/custom/libs
# 3. 再运行程序:
./my_app # 成功加载库!
```