From Source Code to an Executalbe File ----- Learning of Gcc on Linux Operating Systems

Windows make you fool and to learn the computer, you'd better use the linux from now on !

                                                                                                                                      -------By  Dr. Sun

0. Install g++  and gdb on Ubuntu

    sudo apt-get install g++

    sudo apt-get install gdb


1. Compiling your main.c using gcc

     gcc main.c  -o   test


2. From source code to an executable file, four steps are needed.

     1) Preprocessing

          gcc  -E  main.c   -o  main.i

     2) Compilation

          gcc  -S main.i    -o  main.s

     3) Assembly

          gcc  -c   main.s      main.o

     4) Linking

          gcc   main.o   -o    test


3. Make your programs more portable.

      gcc    -Wall   test.c

      gcc    -Werr   test.c


4. Compile multiple source files

     gcc  -c -I ../include  add.c -o add.o
     gcc  -c -I ../include main.c -o main.o

     gcc add.o main.o -o test


5. Compile a lib

     1) Dynamic

          gcc -shared -I ../include add.c -o libadd.so

     2) Static

          gcc -c -I ../include add.c

          ar   r  libadd.a   add.o


6. Use a lib

     1) Dynamic

          export LD_LIBRARY_PATH=/mnt/demo/src
          gcc  -c -I ../include main.c  -o main.o
          gcc -L .  main.o -ladd -o test

     2) Static

          export LIBRARY_PATH=/mnt/fujie/demo/src
          gcc  -c -I ../include main.c  -o main.o
          gcc  -L .  main.o -static -ladd -o test


7. See the loading of the dynamic lib

     ldd test

       

静态库链接时搜索路径顺序:

1. ld会去找GCC命令中的参数-L
2. 再找gcc的环境变量LIBRARY_PATH
3. 再找内定目录 /lib /usr/lib /usr/local/lib 这是当初compile gcc时写在程序内的

动态链接时、执行时搜索路径顺序:

1. 编译目标代码时指定的动态库搜索路径
2. 环境变量LD_LIBRARY_PATH指定的动态库搜索路径
3. 配置文件/etc/ld.so.conf中指定的动态库搜索路径
4. 默认的动态库搜索路径/lib
5. 默认的动态库搜索路径/usr/lib

有关环境变量:
LIBRARY_PATH环境变量:指定程序静态链接库文件搜索路径
LD_LIBRARY_PATH环境变量:指定程序动态链接库文件搜索路径




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章