Sublime Text2搭建C/C++开发环境

[2013.07.08更新,修改不准确的地方]

[2012.11.12更新,添加了编译运行命令]

[PS: 这篇文章主要针对windows平台,但是对其他平台也有参考作用]


(0) 在Sublime Text里边编译程序要求机器上有适当的编译工具,并且要保证可以在命令行里顺利编译。

(1) 配置编译环境

        配置编译环境,就是确保可以在命令行编译源程序,编译工具可以是GCC或VC里的CL。

        如果使用的是GCC(通常是通过安装MinGW获得的GCC及G++),那么只需要把GCC所在的bin目录添加到系统的PATH环境变量里即可;

        如果使用的是CL,原理基本跟GCC一致,但是稍微麻烦一点。如果是VC6.0的话可能不需要配置了,但如果是VC6以上的话就要做下配置,可以参考这篇文章。直到可以在命令行里运行CL命令。

(2) 编辑sublime text的编译配置脚本(如有疑问,请仔细阅读代码中被注释的部分,如下

        在 C:\Documents and Settings\Username\Application Data\Sublime Text 2\Packages\C++\ 目录下找到 C++.sublime-build 文件并打开。请务必把上面目录中的Username替换为本机的用户名。

       如果安装的Sublime Text是Portable版,那就需要到Sublime Text存放位置下的Sublime Text 2\Packages\C++\ 找到 C++.sublime-build 文件。

        然后把C++.sublime-build 里的内容替换为下面的代码:

{
	// "cmd": ["g++", "${file}", "-o", "${file_path}/${file_base_name}"], // For GCC On Windows/Linux 
	"cmd": ["CL", "/Fo${file_base_name}", "/O2", "${file}"],	// For CL on Windows
	"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
	"working_dir": "${file_path}",
	"selector": "source.c, source.c++",
	"encoding":"UTF-8",				// fix encoding!
	
	"variants":
	[
		{
			 "name": "Run",
			// "cmd": ["bash", "-c", "g++ '${file}' -o '${file_path}/${file_base_name}' && '${file_path}/${file_base_name}'"],  // Linux Only
			// "cmd": ["CMD", "/U", "/C", "g++ ${file} -o ${file_base_name} && ${file_base_name}"],  // For GCC On Windows
			"cmd": ["CMD", "/U", "/C", "CL /Fo${file_base_name} /O2 ${file} && ${file_base_name}"]   // For CL On Windows
		}
	]
}

(3) 对上述代码的说明

上面的代码仅仅是在原来的基础了添加了对windows系统上的CL或GCC的支持。

代码的原理很简单,就是在命令行里编译源文件的命令 CL /FoObjectName /O FileName .

下面的文字摘自官方文档Build_Systems,以供参考: http://docs.sublimetext.info/en/latest/reference/build_systems.html

Build Systems

Build systems let you run your files through external programs and see theoutput they generate within Sublime Text.

Build systems consist of two –or optionally three– parts:

  • configuration data in JSON format (the.sublime-build file contents)
  • a Sublime Text command driving the build process
  • optionally, an external executable file (script, binary file)

Essentially,.sublime-build files are configuration data for an externalprogram as well as for the Sublime Text command just mentioned. In them, youspecify the switches, options and environment information you want forwarded.

The Sublime Text command then receives the data stored in the.sublime-buildfile. At this point, it can do whatever it needs tobuild the files. Bydefault, build systems will use theexec command, implemented inPackages/Default/exec.py. As we’ll explain below, you can override thiscommand.

Lastly, the external program may be a shell script you’ve created to processyour files, or a well-known utility likemake ortidy. Usually, theseexecutable files will receive paths to files or directories, along withswitches and options to be run with.

Note that build systems need not call any external program at all if thereisn’t any reason to; you could implement a build system entirely in aSublime Text command.

File Format

.build-system files use JSON. Here’s an example:

{
    "cmd": ["python", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

Options

cmd

Array containing the command to run and its desired arguments. If you don’tspecify an absolute path, the external program will be searched in yourPATH, one of your system’s environmental variables.

On Windows, GUIs are supressed.

file_regex
Optional. Regular expression (Perl-style) to capture error output ofcmd. See the next section for details.
line_regex
Optional. Iffile_regex doesn’t match on the current line, butline_regex exists, and it does match on the current line, thenwalk backwards through the buffer until a line matchingfileregex isfound, and use these two matches to determine the file and line to go to.
selector
Optional. Used whenTools | Build System | Automatic is set totrue.Sublime Text uses this scope selector to find the appropriate build systemfor the active view.
working_dir
Optional. Directory to change the current directory to before runningcmd.The original current directory is restored afterwards.
encoding
Optional. Output encoding ofcmd. Must be a valid python encoding.Defaults toUTF-8.
target

Optional. Sublime Text command to run. Defaults toexec (Packages/Default/exec.py).This command receives the configuration data specified in the.build-system file.

Used to override the default build system command. Note that if you chooseto override the default command for build systems, you can add arbitraryvariables in the.sublime-build file.

env

Optional. Dictionary of environment variables to be merged with the currentprocess’ before passing them tocmd.

Use this element, for example, to add or modify environment variableswithout modifying your system’s settings.

shell
Optional. Iftrue,cmd will be run through the shell (cmd.exe,bash…).
path

Optional. This string will replace the current process’PATH beforecallingcmd. The old PATH value will be restored after that.

Use this option to add directories toPATH without having to modifyyour system’s settings.

Capturing Error Output withfile_regex

The file_regex option uses a Perl-style regular expression to capture upto four fields of error information from the build program’s output, namely:file name,line number,column number anderror message. Usegroups in the pattern to capture this information. Thefile name field andtheline number field are required.

When error information is captured, you can navigate to error instances inyour project’s files withF4 andShift+F4. If available, the capturederror message will be displayed in the status bar.

Platform-specific Options

The windows,osx andlinux elements let you provideplatform-specific data in the build system. Here’s an example:

{
    "cmd": ["ant"],
    "file_regex": "^ *\\[javac\\] (.+):([0-9]+):() (.*)$",
    "working_dir": "${project_path:${folder}}",
    "selector": "source.java",

    "windows":
    {
        "cmd": ["ant.bat"]
    }
}

In this case,ant will be executed for every platform except Windows, whereant.bat will be used instead.

Variables

Build systems expand the following variables in.sublime-build files:

$file_pathThe directory of the current file, e. g.,C:Files.
$fileThe full path to the current file, e. g.,C:FilesChapter1.txt.
$file_nameThe name portion of the current file, e. g.,Chapter1.txt.
$file_extensionThe extension portion of the current file, e. g.,txt.
$file_base_nameThe name only portion of the current file, e. g.,Document.
$packagesThe full path to thePackages folder.
$projectThe full path to the current project file.
$project_pathThe directory of the current project file.
$project_nameThe name portion of the current project file.
$project_extensionThe extension portion of the current project file.
$project_base_nameThe name only portion of the current project file.

Place Holders for Variables

Features found in snippets can be used with these variables. For example:

${project_name:Default}

This will emit the name of the current project if there is one, otherwiseDefault.

${file/\.php/\.txt/}

This will emit the full path of the current file, replacing.php with.txt.

Running Build Systems

Select the desired build system fromTools | Build System, and then selectTools | Build or pressF7.

Troubleshooting Build Systems

Build systems will look for executables in yourPATH, unless you specifyan absolute path to the executable. Therefore, yourPATH variable must becorrectly set.

On some operating systems, the value forPATH will vary from a terminalwindow to a graphical application. Thus, even if the command you are using inyour build system works in the command line, it may not work from Sublime Text.This is due to user profiles in shells.

To solve this issue, make sure you set the desiredPATH so that graphicalapplications such as Sublime Text can find it. See the links below for moreinformation.

Alternatively, you can use thepath element in.sublime-build filesto override thePATH used to locate the executable specified incmd.This new value forPATH will only be in effect for as long as yourbuild system is running. After that, the oldPATH will be restored.


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值