VSCode远程SSH调试树莓派C++时std::cout/printf输出不实时显示问题
解决方案
方案1:全局配置输出缓冲模式(无需修改每一处打印代码)
直接在main函数入口处添加以下代码,一次性配置所有输出的缓冲行为,适合不想挨个添加刷新语句的场景:#include <stdio.h> #include <iostream> int main(int, char**) { // 针对C语言的printf,将stdout设置为行缓冲,遇到换行符自动刷新 setvbuf(stdout, NULL, _IOLBF, BUFSIZ); // 针对C++的std::cout,绑定缓冲同步,输出内容后自动触发刷新 std::ios::sync_with_stdio(true); std::cout.tie(&std::cout); // 后续业务代码无需改动 std::cout << "Hello, world!\n"; std::cout << "Test!\n"; printf("now in C\n"); // ...其他代码 }如果需要完全关闭缓冲(不管有没有换行都实时输出),可以把setvbuf的参数替换为无缓冲模式:
setvbuf(stdout, NULL, _IONBF, 0);方案2:修改launch.json调试配置,强制分配伪终端
远程调试场景下gdb默认会将输出管道设置为全缓冲模式,不会实时刷出内容,在launch.json的配置节点下新增setupCommands配置即可修复:{ "version": "0.2.0", "configurations": [ { "name": "Debug", "preLaunchTask": "cmake", "type": "gdb", "request": "launch", "target": "./build/${workspaceFolderBasename}", "cwd": "${workspaceRoot}", "externalConsole": true, "valuesFormatting": "parseText", // 新增以下配置 "setupCommands": [ { "description": "开启伪终端支持实时输出", "text": "set new-console on", "ignoreFailures": true } ] } ] }如果配置不生效,可在树莓派终端执行
tty命令获取当前伪终端路径,再添加一条配置指定输出终端:{ "text": "set inferior-tty 你获取到的tty路径,例如/dev/pts/0", "ignoreFailures": true }方案3:C++代码用
std::endl代替\n换行std::endl会在输出换行符后自动调用flush操作,不需要手动编写刷新语句,适配调试场景:// 替换前 std::cout << "Hello, world!\n"; // 替换后 std::cout << "Hello, world!" << std::endl;注意高频打印场景下频繁flush会降低性能,调试阶段可以使用该方案,正式发布版本可以改回
\n提升运行效率。
内容的提问来源于stack exchange,提问作者jake_asks_short_questions
相关产品推荐
相关产品推荐

