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_path The directory of the current file, e. g.,C:Files.
$file The full path to the current file, e. g.,C:FilesChapter1.txt.
$file_name The name portion of the current file, e. g.,Chapter1.txt.
$file_extension The extension portion of the current file, e. g.,txt.
$file_base_name The name only portion of the current file, e. g.,Document.
$packages The full path to thePackages folder.
$project The full path to the current project file.
$project_path The directory of the current project file.
$project_name The name portion of the current project file.
$project_extension The extension portion of the current project file.
$project_base_name The 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.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章