1. 程式人生 > >Linux環境下c程序的編譯和執行

Linux環境下c程序的編譯和執行

環境變量 動態 main.c tor direct 環境 沒有 stdlib.h share

1 單個文件的編譯和執行
創建main.c文件,內容如下:

#include <stdio.h>
#include <stdlib.h>

int main(void){
printf("Hello world!\n");
return 0;
};

編譯:

gcc -o main main.o

執行:

root@ubuntu:/ybg/python# ./main
Input an integer:
10
sum=55

2 多個文件的編譯和執行
創建sum.c文件,內容如下:

#include <stdio.h>
#include <stdlib.h>

int
sum(int x){ int i, result=0; for(i=0; i<=x; i++){ result+=i; } if(x > 100) exit(-1); return result; };

創建main.c文件,內容如下:

#include <stdio.h>
#include <stdlib.h>

int main(void){
int x;
printf("Input an integer:\n");
scanf("%d", &x);
printf("sum=%d\n", sum(x));
return 0;
};

編譯

gcc
-c sum.c -fPIC -o sum.o gcc -c main.c -fPIC -o main.o

生成可執行文件,文件名為main

gcc -o main sum.o main.o

執行程序

./main

執行結果同上

3 使用動態鏈接庫方式
生成動態鏈接庫

gcc sum.o -shared -o sum.so

生成可執行文件,文件名為main

gcc -o main sum.o main.o

執行

./main

如果有以下報錯,說明在默認的動態鏈接庫路徑下沒有找到剛剛生成的sum.so

./main: error while loading shared libraries: sum.so: cannot open shared object file: No such file or directory

執行以下命令,將當前目錄添加到動態鏈接庫查找路徑環境變量

export LD_LIBRARY_PATH=pwd:$LD_LIBRARY_PATH

再次執行

./main

執行結果同上

4 python調用.so動態鏈接庫
創建test.py文件,內容如下:

import ctypes
so = ctypes.CDLL(./sum.so)

print "so.sum(50) = %d" % so.sum(50)

執行

root@ubuntu:/ybg/python# python test.py 
so.sum(50) = 1275

Linux環境下c程序的編譯和執行