Beginning Linux Programming 学习--chapter 1 Getting start--What's linux,GNU,HeaderFiles, Libraries
"文明的建立的不是机器而是思想"
Linux truly become a viable operating system, especially in the server market.
In the past, compatibility among different UNIX system has been a real problem. These days, by following a few simple rules, it's possible to create applications that will run on all UNIX and UNIX-like systems.
POSIX: portable operating system interface.
Good Program styles:
1) Simplicity: keep it small and simple
2) Focus: make a program perform one task
3) Reusable components: make the core of your application available as library.
4) Filters: Many UNIX applications can be used as filters. That is, they transform their input and produce output. As you’ll see, UNIX provides facilities that allow quite complex applications to be developed from other UNIX programs by combining them in novel ways. --??
5) Open file formats: eg. XML ,joson
6) flexibility: Try to avoid arbitrary limits on field sizes or number of records. If you can, write the program so that it's network-aware and able to run across a network as well as on a local machine. Never assume that you know everything that the user might want to do.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What's linux?
Linux is a freely distributed implementation of a UNIX-like kernel, the low level core of an operating system. Because Linux takes the UNIX system as its inspiration, Linux and UNIX programs are very similar. In fact, almost all programs written for UNIX can be compiled and run on Linux.
The GNU Project and the Free Software Foundation
Linux owes its existence to the cooperative efforts of a large number of people. The operating system kernel itself forms only a small part of a usable development system. Commercial UNIX systems traditionally come bundled with applications that provide system services and tools. For Linux systems, these additional programs have been written by many different programmers and have been freely contributed.
GNU计划,又称革奴计划,是由Richard Stallman在1983年9月27日公开发起的。它的目标是创建一套完全自由的操作系统,GNU Project is an attempt to create an operating system and development environment that would be compatible with UNIX, but not suffer the restrictions of the proprietary UNIX name and source code. http://www.gnu.org. 原来 先有unix再有GNU。
The GNU Project has already provided the software community with many applications that closely mimic those found on UNIX systems.
A few major examples of software from the GNU Project distributed under the GPL follow:
❑ GCC: The GNU Compiler Collection, containing the GNU C compiler
❑ G++: A C++ compiler, included as part of GCC
❑ GDB: A source code–level debugger
❑ GNU make: A version of UNIX make
❑ Bison: A parser generator compatible with UNIX yacc.--------??
❑ bash: A command shell
❑ GNU Emacs: A text editor and environment
Linux Distributioins:
linux仅仅是一个内核,你可以下载内核源码,编译并安装到机器上,然后,再安装其他的开源软件,构成一个完整的系统! 但是,从源代码来建立一个操作系统的话很费事,幸运的是有人已经做好了可以直接安装的系统,包括kernel和其他的必须软件,即一个完整的系统,这些是可以直接下载的。
These often include an implementation of the X Window System, a graphical environment common on many UNIX systems. The distributions usually come with a setup program and additional documentation (normally all on the CD[s]) to help you install your own Linux system。
Some well-known distributions, particularly on the Intel x86 family of processors, are Red Hat Enterprise Linux and its community-developed cousin Fedora, Novell SUSE Linux and the free openSUSE variant, Ubuntu Linux, Slackware, Gentoo, and Debian GNU/Linux. Check out theDistroWatch site at http://distrowatch.com for details on many more Linux distributions.
可以采用多种语言再linux系统中编写程序:
这些语言很多都是免费的,可以从ftp下载:
Linux Programs:
linux下的应用程序有两种代表: executable and scripts. 可执行的类型可以直接运行,对应于windows系统中的exe程序; scripts是一些解析性命令的集合,对应于windows中的.bat文件,.cmd文件。两种类型的文件可以相互替换,在用户空间没有什么区别!
linux不要求可执行类型的文件有特定的后缀名!
When you log in to a Linux system,you interact with a shell program (often bash)that runs programs in
the same way that the Windowscommand prompt does.
如果你在输入窗口中直接输入一个指令,shell会去到一些列的目录中去搜寻这个命令,这些被搜寻的命令存储在系统变量PATH中。
一般PATH会包含下面几个路径:
❑ /bin:Binaries, programs used in booting the system
❑ /usr/bin:User binaries, standard programs available to users
❑ /usr/local/bin:Local binaries, programs specific to an installation
Note that Linux, like UNIX, uses the colon (:)character to separate entries in the PATH variable,rather than the semicolon (;)that MS-DOS and Windows use.
Remember,Linux uses a forward slash (/) to separatedirectory names in a filename rather than the backslash (\) ofWindows
Emacs是一款功能强大的编辑器!
./fileName,这样写的话,系统会只在当前目录下找fileName,如果不加./系统可能到PATH存储的路径下去寻找,有可能优先运行非当前目录下的同名文件=。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
系统中的各个目录:
/usr/bin :Applicationssupplied by the system for general use, including program development
/usr/local/bin or/opt :Applicationsadded by system administrators for a specific host computer or localnetwork. 管理员把添加的程序放在这里,从而与系统自带的程序分开,当升级系统时,只需要保留这种保存了自己添加的程序的文件夹!
The GNU compiler system’s driverprogram, gcc(which you used in the precedingprogramming
example), is typically located in /usr/binor /usr/local/bin,
其他:
Additional features and programmingsystems may have their own directory structures and program
directories. Chief among these isthe X Window System, which is commonly installed in the /usr/X11or
/usr/bin/X11 directory.
HeaderFiles:
编程时,用到系统函数,库函数时,例如printf时,需要包括头文件。 对于C语言,这些头文件一般被保存在/usr/include目录或者下面的目录。 用gcc编译器进行编译时,应该会自动到这些目录去搜寻头文件。如果你使用的头文件不在这种标准位置,则需要在使用g++时,指定你的额外搜寻目录!例如:
$ gcc -I/usr/openwin/include fred.c
will direct the compiler to look inthe directory /usr/openwin/include,as well as the standard places,
for header files included in the fred.cprogram. Refer to the manual page for the Ccompiler (man gcc)for
more details.
一种在目录中的所有头文件中搜寻某个字符串的方法:
Suppose you need to know the name ofthe #definesused for returning the exit status
from a program. Simply change to the/usr/include directoryand grep fora probable part of the
name like this:
$ grep EXIT_ *.h
...
stdlib.h:#define EXIT_FAILURE 1/* Failing exit status. */
stdlib.h:#define EXIT_SUCCESS 0/* Successful exit status. */
...
Here grepsearches all the files in the directorywith a name ending in .h forthe string EXIT_.In this
example, it has found (among others)the definition you need in the file stdlib.h.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Library Files 库文件---终于等到你
库文件就是编译过程中的object文件。
Libraries are collections of precompiled functions that have been written to be reusable. Typically, they consist of sets of related functions to perform a common task.
系统标准库通常保存在/lib 或者 /usr/lib文件中。 编译器(更准确地说是linker)需要被告知去哪里搜索库,因为默认仅仅搜索标准C库目录。另外,想让编译器找到库文件的话,仅仅把库文件放到标准库的目录中是不够的,还需要让库文件遵循特殊的命名规则,并且需要在commnd line中被指出。
库文件名的命名规则:
A library filename always starts with lib. Then follows the part indicating what library this is (like c for
the C library, or m for the mathematical library). The last part of the name starts with a dot (.), and specifies the type of the library:
❑ .a for traditional, static libraries
❑ .so for shared libraries (see the following)
如何告诉编译器去哪里找库:
You can instruct the compiler to search a library either by giving it the full path name or by using the -l
flag. For example,
$ gcc -o fred fred.c /usr/lib/libm.a
tells the compiler to compile file fred.c, call the resulting program file fred, and search the mathematical library in addition to the standard C library to resolve references to functions. A similar result is achieved with the following command:
$ gcc -o fred fred.c -lm
The -lm (no space between the l and the m) is shorthand (shorthand is much valued in UNIX circles)
for the library called libm.a in one of the standard library directories (in this case /usr/lib). An additional advantage of the -lm notation is that the compiler will automatically choose the shared library when it exists.
Although libraries are usually found in standard places in the same way as header files, you can add to
the search directories by using the -L (uppercase letter) flag to the compiler. For example,
$ gcc -o x11fred -L/usr/openwin/lib x11fred.c -lX11
will compile and link a program called x11fred using the version of the library libX11 found in the
/usr/openwin/lib directory.
Static Libraries( xxx.a)
The simplest form of library is just a collection of object files kept together in a ready-to-use form. When a program needs to use a function stored in the library, it includes a header file that declares the function.-------每个库都最好有一个对应的头文件,指出库函数的形式, 使用方便。
The compiler and linker take care of combining the program code and the library into a single executable program. You must use the –l option to indicate which libraries other than(除了) the standard C runtime library are required.
You can create and maintain your own static libraries very easily by using the ar (for archive) program
and compiling functions separately with gcc -c. Try to keep functions in separate source files as much
as possible. If functions need access to common data, you can place them in the same source file and use static variables declared in that file.
构造static libraries的例子:
1.写C文件 ( fred.c and bill.c) for each function.
fred.c :
#include <stdio.h>
void fred(int arg)
{
printf(“fred: we passed %d\n”, arg);
}
bill.c :
#include <stdio.h>
void bill(char *arg)
{
printf(“bill: we passed %s\n”, arg);
}
2. 分别编译两个C文件,编译成两个目标文件!gcc命令中的-c 意味着要编译成.o文件。另外,因为两个文件中没有main,因此如果要编译成执行文件的话会报错!
$ gcc -c bill.c fred.c
$ ls *.o
bill.o fred.o
3 写一个程序来调用上面生成的.o文件。
为库文件写头文件是一个非常好的习惯,如果其他的程序需要调用库文件中的函数,那么就include这些头文件!It’s a good idea to include the header file in the files fred.c and bill.c too. This will help the compiler pick up any errors.
lib.h :
void bill(char *);
void fred(int);
program.c://调用库函数的程序
#include <stdlib.h>
//#include “lib.h”//*******
int main()
{
bill(“Hello World”);
exit(0);
}
编译:由于现在还没有将bill.o 和fred.o建立成库文件,现在需要在gcc中明确指出这些.o文件:
$ gcc -c program.c //将program.c编译成program.o
$ gcc -o program program.o bill.o //链接 program.o bill.o来生成可执行文件program
$ ./program //run it
bill: we passed Hello World
下面开始建立库函数:
使用ar命令创建archive,并将 program.o bill.o添加进去。(ar creates archives, or collections, of individual files placed together in one large file. Note that you can also use ar to create archives of files of any type. )
$ ar crv libfoo.a bill.o fred.o //将两个object文件搞成库文件libfoo.a,注意库文件的名字要符合约定。
(一些系统,特别是那些源自Berkeley Unix的系统,运行ranlib libfoo.a以后才能使用这个库,但是linux可以不运行这步)
可以这样使用libfoo.a:
$ gcc -o program program.o libfoo.a //
$ ./program
或者这样使用:
$ gcc –o program program.o –L. –lfoo //-lfoo表示需要用到libfoo.a或libfoo.so库,-L. 表示在当前目录先寻找这个库。
To see which functions are included in an object file, library, or executable program, you can use the nm command.
Shared Libraries(xxx.so) ---- 同windows的dll
static library的一个缺点:如果系统同时运行很多个程序,这些程序中都使用到了相同的一个库函数,例如printf, 这样的话prinft就会被很多可执行程序的二进制代码包括,会增大可执行文件的体积,另外,而运行一个程序时系统首先会把该程序调入内存,因此这样内存中有很多份prinf函数的二进制代码(是吗?),会占用很多空间的。 这时便可以用shared library来解决这个问题。
Shared libraries are stored in the same places as static libraries, but shared libraries have a different filename suffix. On a typical Linux system, the shared version of the standard math library is /lib/libm.soshared lib的另一个好处是:可以单独对它们进行升级,不影响其他使用到它们的程序。
可以考虑lib的版本:Symbolic links from the /lib/libm.so file to the actual library revision (/lib/libm.so.N where N represents a major version number — 6 at the time of writing) are used. When Linux starts an application, it can take into account the version of a library required by the application to prevent major new versions of a library from breaking older applications .
---symbolic links,软连接,类似windows中的某个文件的快捷方式文件。
在linux中,负责load shard lib的是ld.so, may be made available as ld-linux.so.2 or ld-lsb.so.2 or ld-lsb.so.3.
自己可以配置额外的搜索shared lib的目录:
The additional locations searched for shared libraries are configured in the file /etc/ld.so.conf, which needs to be processed by ldconfig if changed .
例如,在讲qt的源码安装方法时,有这段话“make sure the lib directory of QT is added to /etc/ld.so.conf 文件。方法是在该文件中写入入qt lib的目录,例如"/usr /lib/qt-3.3/lib",具体跟自己安装的路径有关,可以添加到该文件中的任意位置。 另外,On Fedora and Red Hat Linux systems, the line should be stored in /etc/ld.so.conf.d/qt-i386.conf 。 添加之后,还需要运行一条指令# ldconfig ,需要root权限。” 看来qt的库都是shared lib.
查看可执行文件依赖哪些动态链接库的指令: ldd
$ ldd program
linux-gate.so.1 => (0xffffe000)
libc.so.6 => /lib/libc.so.6 (0xb7db4000)
/lib/ld-linux.so.2 (0xb7efc000)
In this case, you see that the standard C library (libc) is shared (.so). The program requires majorVersion 6.