Basic principles and practice of Linux C language programming

Source: Internet
Author: User
Tags stdin

Basic principles and practice of Linux C programming (2018-06-16-19:12:15)

Basic principles and practice of Linux C language programming

Efficient learning with Purpose: what to do and how to use it

Re-knowledge of C language
    1. C language is a universal, process-oriented programming language, which is widely used in the development of system and application software.
    2. is a way of communication between humans and computers.
    3. ANSI C: Is the standard of C language, in order to avoid the differences in C language syntax for each developer
    4. C language Features: Simple, fast, high performance, good compatibility, powerful, easy to learn

What C language is suitable for
    1. Linux embedded, Gadgets (command-line CD, LS and other commands) small and flexible, simple syntax, suitable for the work of the tool
    2. Hardware-related programs: Operating systems, ARM embedded, microcontroller programming, Arduino programming, etc.
    3. Applications with higher performance requirements: NGINX (c) concurrency = Apache (c + +) * 10
C Suitable for the field
    1. Gadgets (Simple syntax)
    2. Programs for dealing with hardware arm embedded, microcontroller, Arduino programming (with pointers, operable memory)
    3. Programs with high performance requirements

Nginx:c apache:c++

Linux Embedded

Development environment and configuration:
    • C language is a programming language that comes into being with the birth of Unix
    • Mac computer is the UNIX kernel; Linux virtual machines can be installed under Windows

Ubuntu:

    1. Ubuntu and CentOS are more commonly used in Linux distributions, and PCs are better with Ubuntu
    2. Ubuntu's Kylin version is good for Chinese support
    3. AMD64 version: AMD was the first to launch 64-bit CPU, so Ubuntu defined 64-bit CPU model as AMD64 (Intel replicable), has been used to today; 32-bit with x86
    4. LTS version: Long-time technical support version
    5. The Ubuntu system can be either dual-system or a virtual machine can be mounted on the original Windows computer

PS: Try to develop C language program in Linux environment

Common directives
    • Terminal Editor: Emacs vim
    • Install the Software:sudo apt install 【软件名】
    • Update Software:sudo apt update

    • Ctrl+Alt+T: Open Terminal
    • cd ~: Enter the root directory of the current user
    • pwd: View current Path
    • ls: What files are included in the current chapter catalog
    • ls -l: Displays the current file type, permissions, creation time, name
    • ls -alor ll : Show hidden files

If the previous is a d folder, it is - the normal type of file

    • touch **: Create a character file
    • rm **: Delete
    • mkdir **: Create a directory (folder)
    • vi **: Open (Enter) file

VI a non-existent file, entered after the content cannot be entered, because the current in the command mode, by the character I, you can enter the insert mode, you can input content, press ESC to return to the command mode;

In command mode :

    • :w: Save the file
    • :q: Exit
    • i: Inserts a character before the current cursor
    • Shift+i: Jumps to the beginning of the line insert character
    • a: Inserts a character after the current cursor
    • Shift+a: Jumps to the end of the line insert character
    • o: Inserts a character in the current next line
    • Shift+o: Inserts a character on the current line
    • x: Deletes the character at the current cursor
    • d+d: Delete entire row

The best text editor for Linux: Emacs, vim

    • cc -v(gcc -v): View Compiler version

    • Apt-get is a Linux command for the Deb package managed operating system that is used to automatically search, install, upgrade, uninstall software, or the operating system from the Internet's software warehouse.

    • clear: Cleaning the screen

The first C program under Linux

Linux is generally not used void main , the latest C language standards,int main

#include <stdio.h>int main(){    printf("hello,world!\n");    return 0;}
cc a.c

The default will compile and generate the executable file for us a.out (readable writable executable)

    • ./Represents the current path,
    • ./a.outExecutes the a.out file under the current path
    • rRepresents a readable representation of a writable representation of an w x executable

The three groups of repetitions are "creator", "User group", "any other user"

Multiple source files divide and conquer

C language is a structured programming language that supports multiple functions. A program can consist of several functions.

vim hello.c

The most original version of the implementation (HELLO.C):

#include <stdio.h>int max(int a, int b){    if(a>b){        return a;          }else{        return b;    }}int main(){    int a1 = 33;    int a2 = 21;    int maxNum = max(a1,a2);    printf("the max value is %d\n",maxNum);    return 0;}
    • Our stdio.h is built into our user/include.

    • Aligns when you write the Max function, and you write the inner parentheses to indent the alignment.

Additional knowledge: Vim split screen display

    • :sp 文件名Create (Open) a new file
    • On screen:ctrl+w+上箭头
    • Bottom screen:ctrl+w+下箭头
    • Open line number:set nu
    • Cut: (last line number of rows) +dd
    • Paste: P

These two don't need a colon.

    • Close line number: Set Nonu

If the code is directly compiled will be an error, this is an undeclared function.

There are two types of separation schemes:

    • The first is int max(int a,int b); to declare the method in hello.c, and then compile it with the addition of MAX.C
    • One is #include "max.c" then compiled without the need to add max.c together

Version 1:

0-HELLO.C:

#include <stdio.h>int max(int a,int b);int main(){    int a1 = 33;    int a2 = 21;    int maxNum = max(a1,a2);    printf("the max value is %d\n",maxNum);    return 0;}

0-MAX.C:

int max (int a, int b){    if(a>b){        return a;    }else{        return b;    }}

Compile command:

gcc 0-hello.c 0-max.c -o 0-hello.out

If you do not compile with 0-max.c, an error will occur

gcc 0-hello.c -o 0-hello.out/tmp/cc8GuaAH.o:在函数‘main’中:0-hello.c:(.text+0x21):对‘max’未定义的引用collect2: error: ld returned 1 exit status

Version 2

1-HELLO.C:

#include <stdio.h>#include "0-max.c"int main(){    int a1 = 33;    int a2 = 21;    int maxNum = max(a1,a2);    printf("the max value is %d\n",maxNum);    return 0;}

0-MAX.C is consistent with the original

Compile command:

gcc 1-hello.c -o 1-hello.out

If you add more 0-max.c at this point, compile together

gcc 1-hello.c 0-max.c -o 1-hello.out/tmp/ccjcCmVa.o:在函数‘max’中:0-max.c:(.text+0x0): `max‘被多次定义/tmp/cclIxMtD.o:1-hello.c:(.text+0x0):第一次在此定义collect2: error: ld returned 1 exit status

Under Terminal:

    • gcc 文件名.c -o 命名.out
    • Generate. Out and name
    • #include <>Find in pre-assembled libraries
    • #include "max.c"Indicates that a file is found within the current directory

include "max.c"It's equivalent to copying the entire function. The effect is equivalent to writing it in

    • wqais to save multiple files together
header file separated from function definition

Separate the declaration and definition of a function

The code does not execute without the main function, and main is the entry.

    • . h header File
    • . o the intermediate file after compilation
    • . C Source Code
[email protected]:~/Desktop/zjuPlan/CSF878/CCode/linux_c/2-lesson/part1$ ls0-max.c  1-hello.c

Speed up compilation

gcc -c 0-max.c -o 0-max.o

After turning max.c into MAX.O, we need to comment out the include in hello.c and add the method declaration

#include <stdio.h>//#include "0-max.c"int max(int a,int b);

Readable writable non-executable, MAX.O equivalent to the calculator for the source code has been translated into computer-readable machine code

gcc 0-max.o 1-hello.c -o 1-hello.out

Create a new MIN.C

int min (int a, int b){    if(a<b){        return a;    }else{        return b;    }}

Calls to Minnum in hello.c

#include <stdio.h>//#include "0-max.c"int max(int a,int b);int min(int a,int b);int main(){    int a1 = 33;    int a2 = 21;    int maxNum = max(a1,a2);     int minNum = min(a1,a2);    printf("the max value is %d\n",maxNum);     printf("the min value is %d\n",minNum);    return 0;}

Compile command:

gcc -c min.c -o min.o
gcc 0-max.o min.o 1-hello.c -o 2-hello.out

Speed up compilation. No longer modifies the function, public framework, and public class compilation to generate a static library.

The GCC compilation process is divided into 4 steps:

Pre-processing (pre-processing), compilation (compling), assembly (assembling), connection (linking)

Preprocessing: Processing #include #define #ifdef macro Commands

Compiling: Compiling pre-processed files into assembler.s

Compilation: Compiling the assembler .s into a binary .o file

    • gcc -c min.c -o min.oPre-compile file min.c to file min.o
    • cp 文件名a 文件bCopy file A into a new file B
    • Use copy row to copy yy 行号n+yy n rows
    • Use p to paste a copied row
    • Source code files cat can be viewed with commands

Then again, the Max function and the Min function are written by ourselves, even if we do not declare it, we know what parameters are required, what type the parameter is, and what type the return value is. If this function is not written by us, others are written in MAX.O MIN.O we do not see the source code, and we do not know the parameters of the function and return. .hthe benefits of the file are here.

We create a folder Part2

Max.h Code:

int maxNum(int a, int b);

Min.h Code:

int minNum(int a ,int b);

HELLO.C Code:

#include <stdio.h>#include "max.h"#include "min.h"int main(){    int a1 = 33;    int a2 = 21;    int maxNum = max(a1,a2);     int minNum = min(a1,a2);    printf("the max value is %d\n",maxNum);    printf("the min value is %d\n",minNum);}

gcc max.o min.o hello.c -o hello.out

A warning appears, but does not affect the normal compilation run.

The writing of Makfile
    • Make tools can divide large-scale development projects into a number of modules
    • make -v
    • sudo apt-get install make
    • Make tool can be very clear and very quick to organize the source files

The inside of the Make tool is also used by GCC

We develop or install the software to use make and make install these two commands

Because when we have a lot of source files,

gcc max.c min.c hello.c -o hello.out

The command will be long and long.

Writing a makefile can compile multiple files at the same time, telling dependencies.

    • Vim Makefile
    • Write:
hello.out:max.o min.o hello.c      gcc max.o min.o hello.c -o hello.outmax.o:max.c      gcc -c max.cmin.o:min.c      gcc -c min.c# 添加注释
    • Execute commandmake

Write Makefile indent using the TAB key (eight spaces, otherwise an error)

Makefile:3: *** 遗漏分隔符 (null)。 停止。
    • Renaming filesmv MakeFile makefile

Look down from the top and compile it from the bottom up. Files that have been generated are no longer regenerated.

make: “hello.out”已是最新。 (up to date)
Explain in detail the function of the return value in main function and the meaning of the parameter in main function

MAIN.C:

#include <stdio.h>int main(int argc,char* argv[]) //main函数完整形式{    printf("hello,world\n");    return 101;}
gcc main.c -o main.out && ./main.out
    • gcc main.c -o main.out && ./ main.outTwo commands can be executed sequentially
    • return 0Used to verify that the program is running successfully.
    • Command echo $? to view the return value

./main.out && lsPrints out the HelloWorld and lists the current directory. Because the return value of Main.out is 0, it is determined to be executed successfully.

./main2.out && lsPrint out HelloWorld, the current directory is not listed. Because the return value of Main.out is 101 (not 0), it is determined not to be executed successfully.

Parameters in the main function
int main(int argc, char* argv[])//main函数完整形式

ARGC count the number of input parameters. 1 only when you enter a file name

argv[]Store the contents of each parameter
Such as:

    • Input./main3.out-l-A
    • argv = 3
    • Argc[0] =./main.out
    • ARGC[1] =-L
    • ARGC[2] =-A

ARGC (argument count), which holds the number of arguments that are passed into the main function.

argv (argument vector), storing specific incoming parameters

MAIN3.C:

#include <stdio.h>int main(int argc,char* argv[]){    printf("argc is %d\n",argc);    //int i;    for(int i =0;i<argc;i++){    printf("argv[%d]is %s\n",i,argv[i]);    }    return 101;}
$ ./main3.out -a -largc is 3argv[0]is ./main3.outargv[1]is -aargv[2]is -l
Standard input stream output stream and error stream under Linux
    • How the C language is called by the operating system
    • How the operating system passes parameters
    • The return value meaning of the main function

Linux treats everything as a file

    • Standard input stream file: stdin keyboard
    • Standard output stream file: stdout display
    • Standard error Stream file:stderr
    • This is the system default creation
    • fprintf fscanf: put input and output into ...
    • printf("")is the fprintf(stdout,"") encapsulation of the function.
    • scanf("")is the fscanf(stdin,"") encapsulation of the function
#include <stdio.h>int main(){    // printf("hello world!\n");    fprintf(stdout,"hello world \n");    int a;    //scanf("%d",&a);    fscanf(stdin,"%d",&a);    if(a<0){     fprintf(stderr,"the value must >0\n");     # 返回值不等于0表明函数出错     return 1;    }    //printf("input value is: %d\n",a);    return 0;}
Redirection of output and output streams to error streams

Linux can be used in almost any field, and here we have to come up with Linux channels.
管道Play a very important role in the use of different applications , you need to use the pipeline.

Demo:main.c

Understanding the redirect mechanism of the input stream, output stream, and error flow will make it easier to understand the pipeline.

#include <stdio.h>int main(){int i,j;printf("input the int value i:\n"); \\printf其实对fprintf的封装,是从标准输出流(即stdout)来输出这个过程scanf("%d", &i); //默认输入流是键盘printf("input the int value j:\n");scanf("%d", &j);printf("i+j=%d\n", i+j);}
    • Execute the Compile command cc main.c , get a.out , run a.out, we enter 3 and 5 respectively into the terminal.

    • We can use ./a.out 1>> a.txt the command, where the >> symbol (not write parameter is the output stream), before the default output stream is the terminal, now we are output to a.txt, we execute the command, enter 3 back to the car and then enter 5. Then using the command cat a.txt, we can see what we have exported to the file.

Our standard output stream is 1>> that the input stream is0>>

    • We re ./a.out >> a.txt -execute, we re-enter the parameters, once we're done, we'll use it again to view the contents of the A.txt file, and we'll see that the cat new output is appended to the back .

    • To give an example of a redirect, we use the command ls /etc >> etc.txt , we input the contents of the LS directory into the etc.txt file.

    • But if we change the redirect symbol to overwrite the previous content, you can change the double arrow to a >> single arrow > , and the previous content in the file will be overwritten.

Input stream Redirection
    • We can create a file vi input.txt, which reads as follows:
189
    • We execute again ./a.out < input.txt , there is no append mode, so we use a single arrow < , we can all the input content is ready in Input.txt, after the command executes, we can see the result on the terminal.

#include <stdio.h>int main(){    int i,j;    printf("input the int value i:\n");     scanf("%d", &i); //默认输入流是键盘    printf("input the int value j:\n");    scanf("%d", &j);    if(0!=j){           printf("%d/%d=%d\n",i,j,i/j);    }else{        fprintf(stderr,"j != 0\n");        return 1;        }    return 0;}

Note Code specification tips, 0 and J comparison, 0 in front if missing the equals sign will be an error

echo $?View return values

./main.out 1>true.txt 2>false.txt < input.txt
    • Save the output to T.txt.
    • Error saved to F.txt.
    • Read data from Input.txt

Instead of a value error, a 0 error is generated.

It is the operating condition when j=0.

Redirect to another place.

Piping principle and application.

Pipeline:

Use the previous output stream as the input stream for the following tool, with one | representation.

    • grep: View specified text, search for text containing characters

    • Input in Terminal:ls /etc/ | grep ab

  • ls /etc/The input of the output as grep
    • ls /etc/ | grep abFind filenames with AB characters under the/etc/file

    • ps -e: View the process that the system is running
ps -e | grep ssh

To view the process that contains SSH

Practice programming, with simple C language code, write a practical C language applet

AVG.C:

#include <stdio.h>int main(){    int s,n;    scanf("%d,%d",&s,&n);    float v = s/n;    printf("v =%f\n",v);    return 0;}

Compile command:

cc avg.c -o avg.out

INPUT.C:

#include <stdio.h>int main(){    int flag =1;    int i;    int s = 0;    int count=0;    while(flag){    scanf("%d",&i);    if(0==i) break; #等于零跳出    count++;    s+=i;    }    printf("%d,%d\n",s,count);    return 0;}
cc input.c -o input.out

Note that the code above should initialize s to 0. Otherwise, it will cause problems.

When used:

./input.out | ./avg.out

The implementation averages the data between input.

Basic principles and practice of Linux C language programming

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.