Gcc,gdb,makefile and IO multiplexing functions

Source: Internet
Author: User
Tags array length flock strcmp


2015.1.22

C Advanced Environment Construction:
GCC compilers:
Full name GUN CC, is a GNU tool chain, the source code compiled into machine code, the compilation of GCC depends on a lot of gadgets
4.3.3 and 3.4. Version 3 are relatively stable

GCC compilation is divided into four steps: (with the WC command can see the size of each stage code, you can compare, ls-l can see the size)
1. Preprocessing->cpp preprocessing file *.i gcc-e
2. Compiling->CC1 assembly files *.s Gcc-s
3. Compilation of->as assembly documents *.O Gcc-c
4. Link->ld executable file *.exe (combine multiple. o files into an executable application, connector needs to know this target format for work)
Gcc-o or-O2 is compiled and optimized.
Gcc-i dir Specifies the header file directory to add, by default in/usr/include/
LIB + library name. A

Readelf hello-h Display executable file information
Strip discard all or a specific symbol of the target file, reduce the file volume, when you publish the code can be used

Cross-compilation, a compiler that runs in a computer environment, compiles code that runs in a different environment, and we call this compiler to support cross-compiling.
This compilation process is called cross-compiling.
For example: ARM-CORTEX-A8,ARM-LINUX-GCC
GDB Debug Tool: Can execute the program to source code or compile-level debugging
[Email protected]:~/test/gdb# gcc-g e.c-o e generate debug information
[Email protected]:~/test/gdb# gdb e into the debug interface
GNU gdb (GDB) 7.1-ubuntu
Copyright (C) Free Software Foundation, Inc.
License gplv3+: GNU GPL version 3 or later This was free software:you was free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "Show copying"
and "Show warranty" for details.
This GDB is configured as "X86_64-linux-gnu".
For bugs reporting instructions, please see:
Reading symbols From/root/test/gdb/e...done.
(GDB) L (L view files, only 10 lines at a time)
1#include <stdio.h>
2#include <string.h>
3#define N 50
4int Main ()
5{
6int T;
7char S1[n];
8char S2[n];
9
10printf (">");
(GDB) L
11SCANF ("%s%s", S1,S2);
12t = strcmp (S1,S2);
13if (0 = = t)
14printf ("S1 = s2\n");
15else if (T > 0)
16printf ("S1 > s2\n");
+ Else
18printf ("S1 < s2\n");
19return 0;
20
(GDB) L
21}
(GDB) b 11 Set breakpoints on line 11
Breakpoint 1 at 0x4006b8:file e.c, line 11.
(GDB) Info B View breakpoint Information
Num Type Disp Enb Address What
1 breakpoint Keep Y 0x00000000004006b8 in main
(GDB) R runs, stops at the first breakpoint
Starting program:/ROOT/TEST/GDB/E

Breakpoint 1, Main () at E.c:11
11SCANF ("%s%s", S1,S2);
(GDB) n Single Step operation
>2 3
12t = strcmp (S1,S2);
(GDB) S single-step operation
0x00007ffff7adc5a0 in strcmp () from/lib/libc.so.6
At E.c:11
(GDB) P T View the value of the variable T,
$ = 0
(GDB) C recovery Run
Continuing.
S1 > S2

Program exited normally.
(GDB) Help for assistance
List of classes of commands:

Aliases--Aliases of other commands
Breakpoints--Making program stop at certain points
Data--Examining data
Files--Specifying and examining files
Internals--Maintenance commands
Obscure--obscure features
Running--Running the program
Stack--Examining the stack
Status--Status inquiries
Support – Support facilities
Tracepoints--tracing of program execution without stopping the program
user-defined--user-defined commands

Type ' help ' followed by a class name for a list of commands in that class.
---Type <return> to continue, or Q <return> to quit---q
Quit
(GDB) Q (q exit)
[Email protected]:~/test/gdb#

Debugging a section of the program, summarized under:
Array to pay special attention to the scope of the subscript note! Attention! Attention!

1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 int display1 (char *string);
6 int display2 (char *string);
7
8 int main (int argc,char **argv)
9 {
Ten char string[]= "Embedded Linux";
Display1 (string);
Display2 (string);
13
14}
display1 Int (char *string)
16 {
+ printf ("The original string is%s\n", string);
18}
19
int Display2 (char *string1)
21 {
*string2 Char;
Size,i int;
Size = strlen (string1); Array length is 14
string2 = (char *) malloc (size+1);
+ for (i = 0;i < size;i++)
String2[size-i] = String1[i]; should be string2[size-1-i] = string1[i];
String2[size+1] = ' + '; should be string2[size] = ' + ';
printf ("The string afterward is%s\n", string2);
(string2);
31}

SOURCE program Run Result:
[Email protected]:~/test/gdb# gcc gdb.c-o gdb-g
[Email protected]:~/test/gdb#./gdb
The original string is Embedded Linux
The string afterward is//There is no true result here
[Email protected]:~/test/gdb#

To start Debugging:
Reading symbols From/root/test/gdb/gdb...done.
(GDB) b 30 Set breakpoints
Breakpoint 1 at 0x400794:file GDB.C, line 30.
(GDB) R
Starting program:/ROOT/TEST/GDB/GDB
The original string is Embedded Linux
The string afterward is

Breakpoint 1, Display2 (
String1=0x7fffffffe5d0 "Embedded Linux") at gdb.c:30
30free (string2);
(GDB) n
31}
(GDB) P string2[0]
$ = 0 ' \000 '//Word nginx The first address is the value of

To modify the original function:
String2[size-i] = String1[i]; should be string2[size-1-i] = string1[i];
String2[size+1] = ' + '; should be string2[size] = ' + ';

Debugging:

(GDB) B 28
Breakpoint 1 at 0x400768:file GDB.C, line 28.
(GDB) R
Starting program:/ROOT/TEST/GDB/GDB
The original string is Embedded Linux

Breakpoint 1, display2 (
string1=0x7fffffffe5d0 "Embedded Linux") at gdb.c:28
28string2[size] = ' n ';
(GDB) p string2[0]
$ = + x '
(GDB) p string2[14]
$ = 0 ' \000 '
(gdb


Another important feature of GDB is debug freezes and segment errors; it's important,!!!!!.
Example: First write a wrong program core.c name casually write
1 #include <stdio.h>
2 core_function (void)
3 {
4 unsigned char *ptr = 0x00;
5 *ptr = 0x00;
6}
7
8 int main (void)
9 {
Ten core_function ();
return 0;
12
13}
The following are the steps to generate a core (this name is a system-fixed) file:
[Email protected]:~/file# gcc core.c-g//1. Compiling core.c files
[Email protected]:~/file# ulimit-c Unlimited//2. Set Core size to infinity
[Email protected]:~/file# Ulimit Unlimited//3. Set File size to unlimited
[Email protected]:~/file#./a.out//4. Run the compiled file to generate the following core file
Segmentation fault (core dumped)//5. Generating a core file
[Email protected]:~/file# gdb./a.out core//6.gdb Debug, which shows the line of error
Core is generated by './a.out '.
Program terminated with signal one, segmentation fault.
#0 0x00000000004004d4 in Core_function () at Core.c:5
5*ptr = 0x00; 7. Means stop at line 5th and line 4th is wrong.
(GDB)

Software Engineering Tools: Make,cvs,subvision

Make is an engineering management tool that needs to be implemented by makefile (note the uppercase m)
Here is an example demo: contains 4. c files, main.c,f1.c,f2.c,f3.c, and finally writes makefile script
. c files and makefile need to be placed under the same folder

main.c****************************
1 #include <stdio.h>
2 void Enter_string (char str[]);
3 void delete_string (char str[],char ch);
4 void Print_string (char str[]);
5
6 int main (void)
7 {
8 Char c,str[50];
9 enter_string (str);
Ten printf ("The char to being deleted is:");
One scanf ("%c", &c);
Delete_string (STR,C);
13
14}
f1.c**************************************
1 #include <stdio.h>
2 void Enter_string (char str[])
3 {
4 printf ("Input a string:");
5 gets (str);
6
7}
f2.c**************************************
1 void delete_string (char str[],char ch)
2 {
3 int i,j;
4 for (j = i = 0;str[i]! = ' i++ ';
5 {
6 if (str[i]! = CH)
7 Str[j++]=str[i];
8 str[j]= ' + ';
3 ·
10
11}
f3.c****************************************
1 #include <stdio.h>
2 void Print_string (char str[])
3 {
4 printf ("result:%s\n", str);
5
6}


Makefile***************************makefile writing is very strict, there can be no space on both sides, remember!

The following is the target file, followed by the dependent file
Build the command line of the target, can have multiple lines, to the next set of commands start white Oh is the end//1 and 2 make up a group
1 all:main.o f1.o f2.o f3.o
2 Gcc-o all MAIN.O f1.o f2.o f3.o
3 MAIN.O:MAIN.C
4 gcc-c Main.c-o MAIN.O
5 f1.o:f1.c
6 Gcc-c F1.c-o F1.O
7 f2.o:f2.c
8 Gcc-c F2.c-o F2.O
9 f3.o:f3.c
Ten gcc-c F3.c-o f3.o
Clean:
RM main.o F1.O F2.O F3.O
13


Four point C files are compiled together to see if there is anything wrong:

[Email protected]:~/file# gcc-o test main.c f1.c f2.c f3.c
/tmp/ccmczyio.o:in function ' enter_string ':
F1.C: (. text+0x26): warning:the ' gets ' function is dangerous and should not being used.
[Email protected]:~/file# ls
A.out f1.c f3.c FIFO_READ.C test
core.c f2.c fife_write.c main.c write_lock.c

Once the Makefile is written, run make directly:
[Email protected]:~/file# make//Run make
Gcc-c Main.c-o MAIN.O
Gcc-c F1.c-o F1.O
Gcc-c F2.c-o F2.O
Gcc-c F3.c-o F3.O
Gcc-o all MAIN.O f1.o f2.o f3.o
f1.o:in function ' enter_string ':
F1.C: (. text+0x26): warning:the ' gets ' function is dangerous and should not being used.
[Email protected]:~/file# ls
All core.c f2.c f3.o main.c test
A.out f1.c f2.o fife_write.c main.o write_lock.c
Core F1.O f3.c FIFO_READ.C Makefile

The above is the whole process, the following is the analysis:

Variables in the makefile:
1. The variable represents a string, which is automatically expanded when executed in makefile in all used places
2. Variables can be used in targets, dependent targets, commands, or other parts
3. Variables can contain characters, numbers, underscores
4. Variable is case sensitive, the traditional variable is all uppercase
5. The variables within the command line have the highest precedence, the predefined minimum

The format of the variable definition:
Value of variable name assignment symbol variable

There are three types of assignment symbols:

= Assign the following string directly to the variable
: = followed by a variable, assigning its contents to a variable
+ = variable original value + Space + trailing string = = new Variable value

$* does not include a target name for the extension
$+ all dependent files and separated by spaces,
$< the name of the first dependent file
$? All dependent files and separated by spaces, mostly all changed files
[email protected] The full name of the target
$^ all dependent files, separated by spaces, not containing duplicate dependent files

Conditional compilation:
Ifeq
Ifneq
Ifdef
Ifndef
endif//Terminator

For K in $ (DIRS);d o loop body done

Makefile function

SRCS = $ (wildcard *.c)//assigns all point C files in the current directory to SRCs
SRCs = $ (patsubst%.c,%.o,< directory or File >)//Replace All. c files in > < directories or files with. o files and assign to SRCs

%.O:%.c
Gcc-c $<-o [email protected]
The above two sentences mean converting any. c file to an. o file!

To avoid the same name as the file, you can use a special tag ". Phony "to indicate that a target is" pseudo-target "
. Phony:all

After the variable substitution process, the following two makefile functions are the same:

Makefile1:
1 all:main.o f1.o f2.o f3.o
2 Gcc-o all MAIN.O f1.o f2.o f3.o
3 MAIN.O:MAIN.C
4 gcc-c Main.c-o MAIN.O
5 f1.o:f1.c
6 Gcc-c F1.c-o F1.O
7 f2.o:f2.c
8 Gcc-c F2.c-o F2.O
9 f3.o:f3.c
Ten gcc-c F3.c-o f3.o
Clean:
RM main.o F1.O F2.O F3.O
13
Makefile2:
1. Phony:all
2 SRCs = $ (wildcard *.c)
3 DD = $ (patsubst%.c,%.o,$ (SRCS))
4 All: $ (DD)
5 Gcc-o All $+
6 echo $+
7%.O:%.C
8 gcc-c $<-o [email protected]
9 Clean:
Ten RM-RF all $ (DD)
11


File locks can also be divided into read and write locks, where read locks are also known as shared locks, which enables multiple processes to establish a read lock in the same part of the file.
A write lock, also known as a repel lock, can only have one process at any time to create a write lock in one part of the file, not at the same time in the same part of the file
Establish read lock and write lock!!!!

The LOCKF () function is used to apply a proposed lock to a file
The Fcntl () function can not only apply a proposed lock, but also strengthen the lock, while Fcntl can also lock a record of a file, that is, a record lock
It is also a generic function and can perform various operations on open file descriptors, including not only file locks, but also get and set file descriptors
Many features such as flags, file descriptor replication, etc.

int fcntl (int fd,int cmd,struct flock *lock)
0: Success-1: Error

struct flock
{
Short L_type;
off_t L_start;
Short l_whence;
off_t L_len;
pid_t L_pid;

}

Source code for file record lock function:

int lock_set (int fd,int type)
{
struct Flock Old_lock,lock;
Locd.l_whence = Seek_set;
Lock.l_start = 0;
Lock.1_len = 0;
Lock.l_type = type;
Lock.l_pid =-1;

/* Determine if the file can be locked */
Fcntl (Fd,f_getlk,&lock);

if ((lock.l_type! = f_unlck)
{
if (Lock.l_type = = f_rdlck)/* The file */
{
printf ("read lock already set by%d\n", lock.l_pid);
}
else if (Lock.l_type = = F_wrlck)
{
printf ("Write lock already set by%d\n", lock.l_pid);
}
}
/*l_type may have been modified by F_GETLK */
Lock.l_type = type;
/* block lock or unlock according to different type values */
if ((FCNL (fd,f_setlkw,&lock)) < 0)
{
printf ("Lock Failed:type =%d\n", lock.l_type);
return 1;

}
Switch (lock.l_type)
{
Case F_RDLCK:
{
printf ("read lock set by%d\n", Getpid ());
}
Break
Case F_WRLCK:
{
printf ("Write lock set by%d\n", Getpid ());
}
Break
Case F_UNLCK:
{
printf ("Release Lock by%d\n", Getpid ());
return 1;
}
Break
Default
Break

}
return 0;

}

The following instance is a test case for a file write lock, first creating a Hello, and writing a lock on it and releasing the write lock
It contains the upper side of the program Lock_set (FD,F_WRLCK);
#include <unistd.h>
2 #include <sys/file.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #inlcude "Lock_set.c"
8
9 int main (void)
10 {
int FD;
FD = open ("Hello", O_RDWR | o_creat,0644);
if (FD < 0)
14 {
printf ("Open File error\n");
+ exit (1);
17}
/* Read the lock on the file */
Lock_set (FD,F_WRLCK);
GetChar ();
/* Unlock the file */
Lock_set (FD,F_UNLCK);
GetChar ();
Close (FD);
Exit (0);
24


The I/O multiplexing model for select () and poll () is an efficient way to handle I/O reuse.
int select (int numfds,fd_set *readfds,fd_set *writefds,fd_set*exeptfds,struct timeval *timeout)
int poll (struct POLLFD *fds,int numfds,int timeout)

The following procedure calls the Select () function to listen for input from 3 terminals (a virtual terminal directed to two pipe files, respectively) and
The virtual terminal that is run by the main program), and the corresponding processing, respectively,

Multiplex_select.c

1 #include <fcn1.h>
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5 #include <time.h>
6 #include <errno.h>
7
8 #define MAX_BUFFER_SEZE 1024 buffer size
9 #define In_riles 3 multiplexed input File number
#define TIME_DELAY 60 Timeout value seconds
#define MAX (A.B) ((a > B)? (a):(B))
12
int main (void)
14 {
Fds[in_feles int];
(+ char buf[max_buffer_size];
I,RES,REAL_READ,MAXFD int;
Timeval TV with struct;
Fd_set Inset,tmp_inset;
20/* First Open two pipe files in read-only nonblocking mode */
Fds[0] = 0;
if ((fds[1] = open ("in1", O_rdonly | O_nonblock)) <0)
23 {
printf ("Open in1 error\n");
return 1;
26}
if ((fds[2] = open ("in2", O_rdonly | O_nonblock)) <0)
28 {
printf ("Open in2 error\n");
return 1;
31}
32/* Remove the larger of the two file descriptors */
MAXFD = Max (max (fds[0],fds[1]), fd[2]);
/* Initialize the Read collection inset and add the corresponding description set to the Read set */
Fd_zero (&inset);
for (i = 0;i < in_files;i++)
36 {
Panax Notoginseng fd_set (fds[i],&inset);
38}
Fd_set (0,&inset);
Tv.tv_sec = Time_delay;
tv.tv_usec = 0;
42/* Loop tests if the file descriptor is ready to look, and calls the Select function to do the corresponding action on the relevant file descriptor */
while (Fd_isset (fds[0],&inset) | | Fd_isset (fds[1],&inset) | | Fd_isset (Fds[0],&inset))
44 {
/* A backup of the file descriptor, which avoids initializing each time */
Tmp_inset = inset;
-res = SELECT (Maxfd + 1,&AMP;TMP_INSET,NULL,NULL,&AMP;TV);
Switch (RES)
48 {
Case-1:
50 {
* printf ("select error\n");
return 1;
53}
The break;
Case 0:
56 {
* printf ("Time out\n");
1;
59}
break;
The default:
62 {
(i = 0;i < in_files;i++)
64 {
65
memset (But,0,max_buffer_seze);
Real_read = Read (Fds[i],buf,max_buffer_seze);
if (Real_read < 0)
69 {
if (Error! = Eagain)
return 1;
72}
!real_read else if (a)
74 {
Close (Fds[i]);
FD_LCR (Fds[i],&inset);
77
78}
+ Else
80 {
Bayi if (i = = 0)
82 {
/* Main program Terminal control */
if (buf[0]== ' q ') | | (buf[0] = = ' Q '))
return 1;
85}
+ Else
87 {
Buf[real_read] = ' + ';
The BUF printf ("%s",);
90}
91}
92
93}
94}
95}
;
97}
98
return 0;
100}
*************************************************************************************************************** *******************************************
*************************************************************************************************************** *******************************************
*************************************************************************************************************** *******************************************

Gcc,gdb,makefile and IO multiplexing functions

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.