Sublime Text 3 Configuring the C + + compilation Environment

Source: Internet
Author: User
Tags sublime text



Sublime Text 3 provides build functionality that builds systems that can run an external command and capture output and display.



To implement the compilation and operation of C or C + + code in sublime text 3, which is essentially a call to external commands , Windows can also be understood as executing a cmd command.



At present, the most popular is gcc and g++, this article will start from MinGW, introduce the basic command format of GCC and g++, then detail the compilation configuration file in sublime and analyze the function of each line. The build configuration file for C, C + + is then given in Win7 64bit under Sublime Text 3 build 3083.



In addition, the article also introduces the content of using make in Sublime, and discusses the problem of Chinese coding.



If you only want to configure the compilation environment quickly and do not care about implementation details ( not recommended ), you can read only the sections that install MINGW, configure environment variables, and write your own compilation configuration files.


About GCC and g++


Installing the compiler is the basis for all the work behind it, and without the compiler, everything behind it is out of the way. Using GCC and g++ under Windows is implemented by installing MinGW.


Installing MinGW


MINGW is the acronym for Minimalist GNU on Windows and can be installed with a lot of GNU tools. GNU (GNU's not Unix) is a well-known project in Linux and includes tools such as GCC\G++\GDB. In other words, after installing MinGW, we can use the GCC and g++ commands.



MinGW's official website is http://www.mingw.org/, but the installation from the official website is very troublesome, online installation often turtle speed easy to fail.



The recommended method is to use Codeblocks, choose a version with MinGW installation, after installation of the MinGW folder copy it.



Here is a copy of the MinGW that is used to understand the pressure plate, which is reproduced after installation using Codeblocks-13.12mingw-setup:



Http://pan.baidu.com/s/1gd5YzVP



After extracting, we can find the Gcc.exe and g++.exe we need in the Mingw/bin directory.



I'll put the MinGW folder in the C packing directory.








Using gcc in cmd


Suppose we have a test.c file in the work directory of the z-disk. First, we will enter this directory in CMD. You can do this by holding down shift right-click in the work directory and selecting "Open Command Window Here", or you can use the CD command to enter.









The general format of GCC is


GCC source file name-o executable file name





But we enter the command


GCC Test.c-o Test





Prompt after execution



' GCC ' is not an internal or external command, nor is it a running program or batch file.



This is because when the command executes, it looks for an executable file named GCC under the current directory, and if it does not find the GCC executable file in the path record of the system environment variable. But there are none of the two places. The directory where our GCC files are located is the Mingw/bin under C drive.



You can use an absolute path to invoke the GCC executable file


Z:\work>c:/MinGW/bin/gcc test.c -o test
 
Z:\work>test.exe
hello world


This compiles the executable file Test.exe successfully, and then it can be run in CMD.








Configuring Environment variables


For convenience, we usually add the path of GCC to the environment variables of the system, so that you can use the GCC command directly instead of the absolute path.



Environment variables, advanced system settings, properties, right-click Computer









In the value of path, you can find some directories that are separated by semicolons in English .   We double-click on path to add our GCC path C:\MinGW\bin. Be aware of the English semicolon before and after.









Make sure you can use GCC commands directly in any directory. You can open the CMD window in any directory and enter GCC to see if the environment variable is set successfully. If the prompt is still not an internal or external command, the environment variable setting fails.









Note: in sublime text 3 build 3083, changes to the environment variables do not take effect immediately in sublime and require a restart of Windows.


CMD compile run C language


Summarize the process:



First we have to enter the directory where the. c file is in CMD as the working directory



Then execute the GCC source.c-o dest to generate the executable file



Finally, enter the generated executable file name to run the generated program.



We recommend that you join the-wall option to open frequently used warnings.



Here are a few common commands:



Compiling C language


Gcc-wall source file name-o executable file name





Compiling the C + + language


g++-wall source file name-o executable file name





Debugging C + +


g++-G source file name-o executable name gdb executable file name







Sublime Text 3 Default C + + compilation configuration file


Once the g++ is added to the environment variable, the default compilation system in sublime can be used normally.



We open a CPP file in sublime Text 3, press Ctrl+b









This is the default C + + Compile command that sublime comes with. The first one is compile, the second one is run. It can be used normally. ( requires restart of Windows after environment variable configuration)









Sublime Text 3 3080 After the revision of the compilation system, the specific settings are



Ctrl+b executes the last compiled command of the modified format. If the first execution prompts you to choose which



Ctrl+shift+b choose which to execute



Deficiencies:



1. The program output is captured in the sublime window, which results in the inability to enter information when it is run. Code that executes a scanf statement will get stuck.



2. C and C + + are not differentiated by default, and are all treated as C + + format.



Solutions



The first is to set the execution program in the new CMD window so that you can enter information.



The second one is to write a build configuration file for the C language separately.


Default compilation configuration file location


In the Packages folder of the sublime installation directory, there is a file called C++.sublime-package









This is actually a zip compression package, which contains the default system settings for C + +, modify the suffix named zip after decompression , you can find in the C + + single File.sublime-build file.



This file name is the name you can choose to compile.








Compiling the configuration file


The contents of this file are as follows:


{
	"shell_cmd": "g++ \"${file}\" -o \"${file_path}/${file_base_name}\"",
	"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
	"working_dir": "${file_path}",
	"selector": "source.c, source.c++",
 
	"variants":
	[
		{
			"name": "Run",
			"shell_cmd": "g++ \"${file}\" -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
		}
	]
}





This JSON-formatted configuration file is the true face of the build file in sublime. Inside the curly braces are key-value pairs, separated by commas. The middle of the key and value is a colon. For convenience the following keys are called names.



Both the name and the value are enclosed in double quotation marks, so the value inside of the double quotation mark is used as an escape \ "(backslash + double quotation mark).



The name used here has the following meanings:


name meaning
Working_dir Running CMD will first switch to the working directory specified by Working_dir
Cmd Includes commands and their parameters. If you do not specify an absolute path, the external program searches your system's: Const:path environment variable.
Shell_cmd Equivalent to shell:true cmd, CMD can be run through the shell.
File_regex This option uses Perl regular expressions to capture the error output of the build system to the sublime window.
Selector In Selected Tools | Build System | Automatic the system according to this automatic selection.
Variants Alternative to the main building system. That is, a configuration file can correspond to multiple execution commands
Name Only under Variants, set the name of the command, such as run.


There are some similar ${file} symbols in the above configuration file, which are the variables provided by sublime, and some commonly used variables are as follows:


variables meaning
$file _path The directory path where the current file is located, e.g., C:\Files.
$file The detailed path to the current file, e.g., C:\Files\Chapter1.txt.
$file _name Full file name (with extension), e.g., Chapter1.txt.
$file _extension The current file name extension, e.g. txt.
$file _base_name Current file name (not including extension), e.g., Document.


The use of variables can be used directly or enclosed in curly braces, such as ${project_name}.



Let's look at this file in detail.


"Working_dir": "${file_path}",





This line describes the working directory, which is the directory where the command is executed, and is set to the directory where the file resides.



The following


"Shell_cmd": "g++ \" ${file}\ "-o \" ${file_path}/${file_base_name}\ "",





This is the command executed at compile time, and the part of its value is


g++ \ "${file}\"-o \ "${file_path}/${file_base_name}\"





When executed, ${file} will be replaced with the edited file name, and ${file_path}/${file_base_name} will be replaced with the full pathname without the extension. They are preceded by a \ "double quotation mark to support file names with spaces.



Assuming that we edit the file path to Z:/cpp/t.cpp, then the working directory at the time of execution is z:/cpp. ${file} is Z:/cpp/t.cpp, ${file_path} is Z:/cpp, ${file_base_name} is T. We put the escape character Fu Di quotation marks in double quotes, so the executed command becomes


g++ "Z:/cpp/t.cpp"-O "z:/cpp/t"





This is exactly the command to compile the file, and the double quotation marks before and after the file path guarantee that it supports paths with spaces. The executable and source code files generated after compilation are in one directory with the same name (different extensions).



If there is a compilation error, the error message is matched and displayed by the regular expression in "File_regex".



And look at the last code.


"variants":
	[
		{
			"name": "Run",
			"shell_cmd": "g++ \"${file}\" -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
		}
	]





The value of variants is an array that can put many objects, each representing a command. Inside name indicates that the command is named Run, which is running. Selecting C + + single File-run at compile time will execute the shell_cmd.



The first half of the command in the Run section is the same as the compilation, followed by a && connection with another command,&& indicates that the compilation succeeds before performing the subsequent section. Followed by


\ "${file_path}/${file_base_name}\"





That is to run the executable directly. This is to capture the result of the run in the sublime.



After reading this default profile, divert, it's easy to write a profile that fits your needs.



However, it is not recommended to directly modify this file, we recommend that you put the user configuration under the user folder, instead of the default compilation configuration.


Write your own compilation configuration file C language


Select Tool–> Build system–> New build System









Then enter the following code


"variants":
	[
		{
			"name": "Run",
			"shell_cmd": "g++ \"${file}\" -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
		}
	]





Compared to the default, the selector section is modified to select only. c files. in Run, the Shell_cmd is added with the start Cmd/c,start function is a new cmd window, cmd means to execute a command line,/C to exit the new window after execution, after the end of the & pause to ensure that the window will not exit immediately after the run. This will run in the new CMD window.



Press Ctrl+s save, will automatically open the User directory (Sublime Text 3\packages\user), we modified the file name is C.sublime-build, saved in this directory.









At this point, you can see the new C that you just created under Tools--Build system









When selected, it is ready to use.



In addition to selecting a specific compilation system in the build systems, you can also select the first: Automatic automatic selection, which is automatically selected based on the file suffix that is opened. Because the. c file Sublime is recognized as a C + + type by default, you need to modify one point when using automatic selection:



The default is C + + format when opening a. c file with sublime first. (Note: The latest version of 3013 is already in C format, you do not have to modify it)









Click c + + at the red arrow to select Open all with the current extension as. Then select C









This will open the. c file by default to C type



Press Ctrl+shift+b at this time









The third c is the corresponding execution of the third line in the configuration file Gcc-wall $file _name-o $file _base_name function is compiled.



Fourth C-run corresponds to the following command Gcc-wall $file-o $file _base_name && start cmd/c \ "${file_path}/${file_base_name} & Pause\" , the function is to run in a new CMD window. This makes it possible to enter functions such as scanf.


C++


Although GCC can compile C + + code, it cannot do the C + + connection function library operation. So for C + + code generally use g++ to compile.



Method and the above C language configuration, as long as the configuration file in the GCC changed to g++, source.c to source.c++, save the file name C.sublime-build changed to C++.sublime-build.



This adds the-STD=C++11 option, which is compiled according to the C++11 standard, which can be removed if not required, and the configuration file is as follows


{
	"encoding": "utf-8",
	"working_dir": "$file_path",
	"shell_cmd": "g++ -Wall -std=c++11 \"$file_name\" -o \"$file_base_name\"",
	"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
	"selector": "source.c++",
 
	"variants": 
	[
		{	
		"name": "Run",
        	"shell_cmd": "g++ -Wall -std=c++11 \"$file\" -o \"$file_base_name\" && start cmd /c \"\"${file_path}/${file_base_name}\" & pause\""
		}
	]
}





In fact, we can use Varians to configure several different compile commands.



The following configuration files are compiled, compiled and run in Sublime, compiled and Cmd run, and gdb debugs four commands.



Note:gdb debugging is the way to open the command line, there is no support for the source code with spaces file name and path,gdb use can refer to: GdB debugging Novice (a) | Aloft. To achieve graphical debugging through the SUBLIMEGDB plug-in, you can refer to sublime Text 3 using sublimegdb graphical Debug/C + + program.





{
	"encoding": "utf-8",
	"working_dir": "$file_path",
	"shell_cmd": "g++ -Wall -std=c++11 \"$file_name\" -o \"$file_base_name\"",
	"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
	"selector": "source.c++",
 
	"variants": 
	[
		{	
		"name": "Run in sublime",
        	"shell_cmd": "g++ -Wall -std=c++11 \"$file_name\" -o \"$file_base_name\" && cmd /c \"${file_path}/${file_base_name}\""
		},
		{	
		"name": "CMD Run",
        	"shell_cmd": "g++ -Wall -std=c++11 \"$file\" -o \"$file_base_name\" && start cmd /c \"\"${file_path}/${file_base_name}\" & pause\""
		},
		{	
		"name": "gdb Debug",
        	"shell_cmd": "g++ -g -std=c++11 \"$file\" -o \"$file_base_name\" && start cmd /c gdb ${file_path}/${file_base_name} & pause"
		}
	]
}




Compiling multiple files with makefile


Sublime can use makefile to compile multiple files to support a slightly larger project. (Windows below and Linux below are not the same, this article describes for Windows)



This feature only opens a single file that is not available, only open the entire folder









You can see the open folder in the sidebar to make sure that the folder contains the makefile file. When you press CTRL+SHIFT+B, there is an option to make.



The Make option is done here, but there is no make command in Windows. The name inside the Mingw\bin is Mingw32-make.exe. The workaround is to change the file name to Make.exe, or create a new makefile build file yourself.



The default compilation profile for Makefile is in the "C:\Program files\sublime Text 3\packages\makefile.sublime-package", extracted from the Make.sublime-build file.



We created a new build system,tool–> build system–> New build systems with the contents of



Note: The file is tested in the sublime 3126 version, the lower version may not support the KeyFile keyword, or there is no packages/makefile/make Output.sublime-syntax files, you can upgrade or try to delete these rows


{
	"shell_cmd": "mingw32-make",
	"file_regex": "^(..[^:\n]*):([0-9]+):?([0-9]+)?:? (.*)$",
	"working_dir": "${folder:${project_path:${file_path}}}",
	"selector": "source.makefile",
	"syntax": "Packages/Makefile/Make Output.sublime-syntax",
	"keyfiles": ["Makefile", "makefile"],
 
	"variants":
	[
		{
			"name": "Clean",
			"shell_cmd": "mingw32-make clean"
		},
		{
			"name": "Run",
			"shell_cmd": "mingw32-make run"
		},
	]
}





Save As Mingw32-make.sublime-build, save location and the above C + + configuration file location is the same.



Then open the folder, if there is makefile or makefile file, there will be a corresponding command









Because the common commands under Windows are different from Linux, makefile also makes the corresponding changes:


Makefile Example


The following is a simple example:



Now there is a test folder with 4 files in it









Where Main.cpp used the function in the func.cpp. The specific code is as follows:



Main.cpp


 
#include "func.h" int main()
{
    output(); return 0;
}





Func.h


void output ();





Func.cpp


#include <cstdio> void output()
{
    printf("hello world\n");
}





Makefile


main : main.cpp func.h func.cpp
 
 
clean:
	del main.exe *.o
 
run:
	mingw32-make && start cmd /c "main.exe & pause"





Note: The makefile inside the clean and run, and our own configuration file "variants" under the command Mingw32-make clean and mingw32-make run corresponding.



Clean below use the command for del instead of the RM below Linux



In addition, because there is no CC command under Windows, all dependencies cannot occur here. o the target of the file. For example, there is no such rule:


MAIN:MAIN.O FUNC.O





When you use such a rule, CC is called, but CC is not available under Windows, and you get an error.



Open the folder in sublime text 3 ( Note that you must open the folder, only open the file without the make option)









Then use Ctrl+shift+b to select the corresponding Mingw32-make command.









Run corresponds to compile and run.








The problem of Chinese code garbled


Thank rgb0x000000 for pointing out the problem of Chinese coding. Because the default encoding format for files in Sublime Text 3 is utf-8, the command line default encoding format in Windows is GBK. So the code in Chinese when the run will be garbled.



The solution is also very simple, is to let them code consistent on it.


1. Change the cmd code to Utf-8


Use the CHCP command to view the current character set, which is 936 by default, and you can use CHCP 65001 to modify the character set to Utf-8



However, it seems to be only valid for the currently open window, one troublesome way is to run the system in each code to toggle the character set (POP)


2. Modify the source code format to GBK


Sublime native does not support GBK encoding, but if the ConvertToUTF8 plugin is installed, ANSI or GBK encoded files can be displayed correctly. Therefore, the plug-in after the open GBK encoded source code files, will not garbled.



A more ingenious approach is to use the compiler's option -fexec-charset to set the encoding of the string in the code so that the source file can use Utf-8 encoding, but compiles the string in the source code with the specified encoding.



Add the option -FEXEC-CHARSET=GBK to the compile command GCC to show that the string in the code is encoded in GBK, and that it is consistent with the CMD window and is not garbled.



The configuration file for the modified C language is as follows:


{
	"working_dir": "$file_path",
	"cmd": "gcc -Wall -fexec-charset=GBK \"$file_name\" -o \"$file_base_name\"",
	"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
	"selector": "source.c",
 
	"variants": 
	[
		{	
		"name": "Run",
        	"shell_cmd": "gcc -Wall -fexec-charset=GBK \"$file\" -o \"$file_base_name\" && start cmd /c \"\"${file_path}/${file_base_name}\" & pause\""
		}
	]
}





But after adding this option, if you want to compile not utf-8, but GBK, you must also add the-FINPUT-CHARSET=GBK option to develop the encoding format of the source code, otherwise it will prompt the error



Error:converting to execution character Set:illegal byte sequence.



and add this option after compiling utf-8 will be garbled ... So, at present, Bo Master has not found the source file is Utf-8 encoding and GBK encoding two cases Chinese will not garbled method ...



Transferred from: http://www.yalewoo.com/sublime_text_3_gcc.html



Yalewoo



Sublime Text 3 Configuring the C + + compilation environment (RPM)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.