Basic knowledge of C/C ++ programming using Vim in Linux

Source: Internet
Author: User
Tags mathematical functions set background

(Prerequisites)

Learn VIM: http://www.cnblogs.com/starspace/archive/2009/05/15/1458044.html

Configure VIM: http://haohetao.javaeye.com/blog/690715

 

Summary:Install Vim --> Configure the/etc/Vim/vimrc File

This 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 Vim test. cpp and create a new file named "test. cpp". If you have already created this file, open the file named "test. cpp.

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 <iostream>
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 <stdio. h>
Int main (void)
{
Printf ("Hello, world! /N ");
Return 0;
}

Run the "gcc-wall test. C-o testc" command during compilation. Note that the C ++ library cannot appear in the C file, for example, # include <iostream. h> 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 <iostream>
Using namespace STD;
# Include "test. H"
 
Void test (const char * name)
{
Cout <"Hello world! "<Endl;
}

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 object files 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 <math. h>
# Include <stdio. h>
 
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.

 

 

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.