代码改变世界

Sublime Text2 编译和运行C/C++程序(windows)

2013-01-02 23:50  Rudrj2  阅读(40790)  评论(5编辑  收藏  举报

Sublime Text2的高亮显示代码,非常好用,界面也非常漂亮,Sublime Text2工具栏有编译项,所以想让它来编译C和C++代码,不想每次几行代码也都打开visual studio,网上有gcc的解决方案。我想用微软的编译器,因为电脑里面已经装了Visual studio 2010,所以想用系统已有的编译器了.

<1>  如果你的编译环境是GCC并且已经可以在命令行里用gcc编译源文件,那么Sublime Text2不要任何配置就可以对单个源文件进行编译和运行,下面的东西可以不看了。

<2> 如果没有GCC或者就是希望用Visual Studio里的编译器CL进行编译运行,那么你可以安装下面的操作完成配置。

 


 

一、利用VS2010搭建命令行编译环境

本人机子是vista,在“我的电脑”上,右键找到“属性”,选择“高级系统设置”,进到“环境变量”里面;

(1)创建三个系统变量

  在命令行输入set命令会有对应的VS信息,vs2010是VS100COMNTOOLS

<1>名字: VS100Common

       值: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7

<2>名字: VS100VC

       值: C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC

<3>名字: VS100SDK

       值: C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A

(2)创建(或追加)三个用户变量

<1>名字: PATH

值 :%VS100VC%\BIN;%VS100Common%\IDE;%VS100Common%\TOOLS;%VS100SDK%\BIN;%PATH%

<2>名字: INCLUDE

值 :%VS100VC%\INCLUDE;%VS100VC%\ATLMFC\INCLUDE;%VS100SDK%\INCLUDE;%INCLUDE%

 

<3>名字: LIB

值 :%VS100VC%\LIB;%VS100VC%\ATLMFC\LIB;%VS100SDK%\LIB;%LIB%

(3)打开终端运行cl,如果没有提示非命令的话,基本配置成功了,本人机子是vista直接重开cmd就可以运行了。。如果其他系统无法运行的话,考虑重启。

(4)随便写一个程序:

#include <iostream>

using namespace std;
int main()

{
    unsigned int a = ~0;
    if( a>65536 )
    {
    cout<<"32 bit"<<endl;
    }
    else
    {
    cout<<"16 bit"<<endl;
    }
    return 0;
}

(5)编译运行:



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

(1)打开Sublime Text2,选择tools,然后选择Build System,然后选择 New Build System。

  然后在里面输入下面的代码:

 

 1 { 
 2       "cmd": ["CL", "/Fo${file_base_name}", "/O2", "${file}"],   
 3       "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",  
 4       "working_dir": "${file_path}",  
 5       "selector": "source.c, source.c++",  
 6       "encoding":"cp936",
 7 
 8 
 9       "variants":  
10       [  
11            {  
12               "name": "Run", 
13               "cmd": ["CMD", "/U", "/C", "CL /Fo${file_base_name} /O2 ${file} && ${file_base_name}"] 
14           }  
15 16     ]  
16 17 }  

 

 

(2)然后保存为:MSComplie.sublime-build,注意后缀一定为sublime-build。

上面的代码仅仅是在原来代码的基础了针对windows平台下CL的修改了两节,同时加了几个逗号,并且修改了编译环境的编码,因为默认的Sublime Text 2的编码是UTF-8。。

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

 

打开上面那个demo测试下:ctrl+B编译

 

 

 

Ctrl+Shift+B运行程序界面如下

 

如果编译运行时遇到如下错误:

 


 

LINK : fatal error LNK1104

你编译产生的***.exe文件已经装入内存了,故编译好以后无法将编译后的 ***.exe文件覆盖上去。只需要打开任务管理进行关闭对应的EXE进程。

 


 

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

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 PATHvalue 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 numberfield 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.