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環境變量:指定程序動態鏈接庫文件搜索路徑




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