Home >Operation and Maintenance >Linux Operation and Maintenance >How to compile and execute c program in Linux environment? (detailed explanation)

How to compile and execute c program in Linux environment? (detailed explanation)

青灯夜游
青灯夜游forward
2018-10-25 16:47:564842browse

The content of this article is to introduce how to compile and execute c programs in the Linux environment? (detailed explanation). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1 Compilation and execution of a single file

Create the main.c file with the following content:

#include <stdio.h>#include <stdlib.h>int main(void){
printf("Hello world!\n");return 0;
};

Compilation:

gcc -o main main.o

Execution:

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

2 Compilation and execution of multiple files
Create the sum.c file with the following content:

#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;
};

Create the main.c file with the following content :

#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;
};

Compile

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

Generate an executable file, the file name is main

gcc -o main sum.o main.o

Execution program

./main

The execution result is the same as above

3 Use the dynamic link library method

Generate the dynamic link library

gcc sum.o -shared -o sum.so

Generate the executable file, the file name is main

gcc -o main sum.o main.o

Execute

./main

If the following error is reported, it means that the newly generated sum.so was not found in the default dynamic link library path

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

Execute the following command to add the current directory to the dynamic link library search path environment variable

export LD_LIBRARY_PATH=pwd:$LD_LIBRARY_PATH

Execute again

./main

The execution result is the same as above

4 python calls the .so dynamic link library

Create the test.py file with the following content:

import ctypes
so = ctypes.CDLL('./sum.so')print "so.sum(50) = %d" % so.sum(50)

Execute

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

The above is the detailed content of How to compile and execute c program in Linux environment? (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete