Use Vim for C/C ++ programming in Linux

Source: Internet
Author: User
Tags mathematical functions
Conclusion: install vim -- configure the/etc/vim/vimrc file so that vim can support syntax highlighting, automatic indentation, and other functions. Currently, the content of the vimrc configuration file is as follows, and basic c/c ++ programming is enough. ++

Summary:Install vim --> configure the/etc/vim/vimrc fileThis enables vim to support syntax highlighting, automatic indentation, and other functions. Currently, the content of the vimrc configuration file is as follows, and basic c/c ++ programming is enough.

++

"Syntax highlighted
Syntax enable
Syntax on
Set background = dark
Set nocompatible
Set number

"Check file type
Filetype on

"Number of historical rows recorded
Set history = 1000
Set cursorline

"Set autoindent
Set cindent

"Set the specific indent mode of C/C ++ language
Set cinoptions = {s, t0, n-2, p2s, (03 s, =. 5 s,> 1 s, = 1 s,: 1 s
Set smartindent
Set expandtab "uses spaces instead of tabs.
Set ts = 4 "number of spaces
Set shiftwidth = 4 "Auto Indent width
Set showmatch
Set cursorline
Set nobackup

"Just for encode
Set fileencodings = UTF-8, gb2312, gbk, gb18030
Set termencoding = UTF-8
Set fileformats = unix
Set encoding = prc
Set hlsearch "highlight all matches

"Set foldmethod
Set OFDM = indent "code folding

If & term = "xterm"
Set t_Co = 8
Set t_Sb = ^ [4% dm
Set t_Sf = ^ [3% dm
Endif

++

Vim has powerful functions. you can DIY the vimrc file based on your own needs, which can produce extraordinary results. for details, see the following:

Http://blog.csdn.net/wooin/archive/2007/10/31/1858917.aspx

(1) coding 

1. Start the terminal;

2. Input vimtest. cpp and create a new file named "test. cpp". if this file has been created before, open the file named.

3. The command mode is entered by default. input I, a, and o enter the edit insert mode, which corresponds to the current position before, after, and insert a row.
If you want to delete the content of the row being edited (delete a character, delete a word, delete a line), you must press esc to return to the command mode, use x (delete one character), dw (delete one word), and dd (delete one row) to delete the data respectively.
If you want to cancel an operation, return to the command mode, and enter the command u (undo) to cancel the operation. if you want to restore the undo content, enter the command ": redo "or": Control key + r "can be undone and restored multiple times without compatible;

4. After the editing is complete, enter ": w" to save the disk, and then enter ": q" to exit the vim editor. you can also directly enter ": wq" to complete these two steps.

(2) code compilation and running 

Set the content of the "test. cpp" file:
# Include
Int main (int argc, char * argv [])
{
Std: cout <"hello, world/n ";
Return 0;
}

1.For this. cpp file, use the following command to compile the file:
Gcc-Wall test. cpp-o test-lstdc ++ (The-lstdc ++ option must be added to notify the linker to link to the static library libstdc ++. a. Otherwise, an error occurs because the library function cannot be found)
Or directly use the command g ++ for compiling the c ++ (. cpp) file, as follows:
G ++-Wall test. cpp-o test

====================
This command compiles the code in the file 'test. cpp 'into a machine code and stores it in the executable file 'test. The name of the machine code file is specified through the-o option, which is usually used as the last parameter in the command line. If omitted, the default output file is 'a. out '.

Note that if the file with the same name as the executable file already exists in the current directory, it will be overwritten.

Option-Wall enables almost all common warnings of the compiler-it is strongly recommended that you always use this option. The compiler has many other warning options, but-Wall is the most commonly used. By default, GCC/G ++ does not generate any warning information. When writing C or C ++ programs, the compiler warning is very helpful for detecting program problems.

In this example, the compiler uses the-Wall option without generating any warning, because the example program is completely legal.

In addition, if a c-language file named "test. c" is created at the beginning, the content is as follows;
# Include
Int main (void)
{
Printf ("Hello, world! /N ");
Return 0;
}

Run the "gcc-Wall test. c-otestc" command during compilation. Note that the c ++ library cannot appear in the c file, for example, # include An error is reported, but the cpp file contains a library of C language.

====================

2.Run:
$./Test
====================
This command loads executable files into the memory and enables the CPU to start executing the commands contained in the files. Path "./" refers to the current directory, so "./test" loads and executes the executable file 'test' under the current directory '.
====================
Running result: hello, world

(3) compile multiple source files 

1.Multi-source file example
The preceding "test. cpp" is divided into three different files: 'Main. cpp ', 'Test _ fn. cpp', and the header file 'test. H '.
(1) the main program 'main. cpp 'is as follows:
# Include "test. h"
Int main ()
{
Test ("hello world! ");
Return 0;
}

(2) the function declaration file "test. h" is as follows:
Void test (const char * name );

(3) the content of the function implementation file "test_fn.cpp" is as follows:
# Include
Using namespace std;
# Include "test. h"
Void test (const char * name)
{
Cout <"HelloWorld! "< }

2.Multi-file compilation
G ++-Wall main. cpp test_fn.cpp-o newTest
==================================
In this example, we use option-o to specify a different name newTest for the executable file. Note that the header file 'test. H' is not specified in the command line because it is already included in main. cpp.
==================================

(4) simple makeFile 
The make command reads the description of the project from makefile (the 'makefile' file in the current directory by default. Makefile specifies the compilation rules for a series of targets (such as executable files) and dependencies (such as object files and source files). The format is as follows:
Target: Dependency
Command
For each target, make checks its corresponding dependent file modification time to determine whether the target needs to be re-created using the corresponding command. Note that the command line in makefile must be indented with a single TAB character, not a space (correct: it is a space rather than a TAB ).

GNU Make contains many default rules (see implicit rules) to simplify makefile construction. For example, they specify that the '. O' file can be obtained by compiling the'. c' file, and the executable file can be obtained by linking '. O' together. Implicit rules are specified by something called make variables, such as CC (C language compiler) and CFLAGS (C program compilation options ); in the makefile file, they are set in the form of a variable = value exclusive to a row. For C ++, the equivalent variables are CXX and CXXFLAGS, while the variable CPPFLAGS is the compilation preprocessing option.

1.Create a simple makefile file for the above example of "compiling multiple source files". The content is as follows:
CXXC = g ++
CXXFLAGS =-Wall
NewTest: main. o test_fn.o (uses the implicit rule cpp --> o)
Clean: rm-f newTest main. o test_fn.o

==============================
The makefile file can be read as follows: use the C ++ language compiler g ++, and the compilation option '-wall', from the object file 'test. o' and 'test _ fn. o 'generates the target executable file newTest (file 'test. o' and 'test _ fn. o 'uses the implicit rules by 'test. c' and 'test _ fn. c ). The target clean does not depend on files. it simply removes all compiled files. Rm command option '-f' (force) to suppress the error message generated when the file does not exist.
==============================
2.To use the makefile, enter the make command. When you call make without parameters, the first target in the makefile is created to generate the executable 'newtest'. The terminal will have the following output:

$ Make
G ++-Wall-c-o main. o main. cpp
G ++-Wall-c-o test_fn.o test_fn.cpp
G ++ main. o test_fn.o-o newTest
Run the executable file:
$./NewTest
Hello, world!

3.If a source file is modified, you need to generate the executable file again. simply enter make again. By checking the timestamp of the target and dependent files, the program make can identify which files have been modified and update their target files according to the corresponding rules:

$ Vim test. cpp (if you open the editor and modify the test. cpp file)
$ Make (re-make)
G ++-Wall-c-o test. o test. c (in this case, only make the modified file test. cpp)
G ++ test. o test_fn.o-o newTest

Run:
$./NewTest
Hello, world!
4.Finally, remove the file generated by make and enter "make clean". the output is as follows:
$ Make clean
Rm-f hello. o hello_fn.o

Summary: The makefile file is similar to a batch file for compiling and connecting programs. all the commands are written into a file called makefile, then run the make command to execute the makefile file similar to the batch file. A professional makefile file usually contains additional targets such as make install and make check.
The examples involved in this example are simple enough that makefile is not required at all, but it is necessary to use makefile for any larger program.

(5) link external libraries

A library is a collection of pre-compiled target files (objectfiles) that can be linked to a program. The static library is stored as a special archive file with '..

The standard system library can be found in the/usr/lib and/lib directories. For example, in Unix-like systems, the C-language mathematical library is generally stored as a file/usr/lib/libm.. The prototype declaration of the function in this library is in the header file/usr/include/math. h. The C standard library is stored as/usr/lib/libc. a, which contains functions specified by the ANSI/iso c standard, such as 'printf '. For every C program, libc. a is linked by default.

The following is an example of calling the sin function in the library libm. a. create the file calc. c:

# Include
# Include
Int
Main (void)
{
Double x = sin (0, 2.0 );
Printf ("The value of sin (2.0) is % f/n", x );
Return 0;
}

An attempt to generate an executable file from this file will result in a link phase error:

$ Gcc-Wall calc. c-o calc
/Tmp/ccbR6Ojm. o: In function 'main ':
/Tmp/ccbR6Ojm. o (. text + 0x19): undefined reference to 'sin'

Function sin, which is not defined in this program and is not in the default library 'libc. a'. Unless specified, the compiler will not link 'libm. '.

1. Method 1
To enable the compiler to link sin to the main program 'calc. C', we need to provide the math library 'libm. '. One easy-to-think but troublesome way is to explicitly specify it in the command line:

$ Gcc-Wall calc. c/usr/lib/libm. a-o calc

The function library 'libm. a' contains the target files of all mathematical functions, such as sin, cos, exp, log, and sqrt. The linker searches all files to find the target file containing the sin. Once the target file containing sin is found, the main program can be linked and a complete executable file can be generated:

$./Calc
Value of sin (2.0) is 0.909297

The executable file contains the machine code of the main program and the machine code of sin in the 'libm. a' function library.

2. Method 2 
To avoid specifying a long path in the command line, the compiler provides a quick option '-L' for the linked function library '. For example, the following command

$ Gcc-Wall calc. c-lm-o calc

It is equivalent to the command '/ usr/lib/libm. a' for the specified full path of the library above.

In general, option-lNAME enables the linker to try to link the library file libNAME. a in the system Library Directory. A large program usually uses many-l options to specify the math library, graphics library, and network library to be linked.

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.