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

Sublime Text配置C++编译环境遇输入重定向错误求助

解决Sublime Text中C++编译时输入重定向的链接错误

问题描述

配置Sublime Text的C++开发环境,使用MSYS MinGW作为编译工具,创建file.cpp、inputf.in、outputf.out文件后,编写了Build System配置,但编译时出现两个问题:

  • 程序无法读取inputf.in的输入
  • ld.exe报错,将inputf.in识别为链接脚本并提示语法错误

错误信息如下:

C:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/13.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe:C:\Users\Admin\Desktop\codeforces\inputf.in: file format not recognized; treating as linker script
C:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/13.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe:C:\Users\Admin\Desktop\codeforces\inputf.in:1: syntax error
collect2.exe: error: ld returned 1 exit status
[Finished in 136ms]

原Build System配置:

{
    "cmd": ["g++.exe", "-std=c++17", "${file}",
            "-o", "${file_base_name}.exe",
            "&&", "${file_base_name}.exe<inputf.in>outputf.out"],
    "shell":true,
    "working_dir":"$file_path",
    "selector":"source.cpp"
}

问题原因

当shell=true时,Sublime会将cmd数组中的每个元素作为独立参数传递给shell。原配置中,&&、${file_base_name}.exe<inputf.in>outputf.out被错误当成g++.exe的编译参数,导致g++把inputf.in视为需要链接的目标文件,进而触发ld.exe的语法错误。

解决方法

将编译和运行的整个命令合并为单个字符串,让shell正确解析命令分隔符&&和输入输出重定向符号:

修改后的Build System配置(推荐方式)

{
    "shell_cmd": "g++.exe -std=c++17 \"${file}\" -o \"${file_base_name}.exe\" && \"${file_base_name}.exe\" < inputf.in > outputf.out",
    "working_dir": "${file_path}",
    "selector": "source.cpp"
}

替代方案(保留cmd字段)

{
    "cmd": ["g++.exe -std=c++17 \"${file}\" -o \"${file_base_name}.exe\" && \"${file_base_name}.exe\" < inputf.in > outputf.out"],
    "shell": true,
    "working_dir": "${file_path}",
    "selector": "source.cpp"
}

说明

  • 使用shell_cmd是Sublime推荐的方式,它会直接将字符串传递给shell解析,避免数组参数拆分的问题
  • 添加引号\"是为了处理文件名或路径含空格的情况,确保命令正确执行
  • 修改后,shell会先执行编译命令,成功后再运行生成的exe程序,自动将inputf.in作为输入,输出写入outputf.out

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 04:10:56