Get the App
SLTechnology News&Howtos  ›  Servers  › 

The method of compiling and executing c Program in Linux Environment

Shulou Source: shulou.com Published: 2022-06-02 04:20:39 09月25日 Update

This article will explain in detail the methods of compiling and executing c programs under the Linux environment. The editor feels that it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

1 compilation and execution of a single file

Create a main.c file as follows:

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

Compile:

Gcc-o main main.o

Execute:

Root@ubuntu:/ybg/python#. / mainInput an integer:10sum=55

2 compilation and execution of multiple files

Create a sum.c file as follows:

# include # include int sum (int x) {int I, result=0;for (iTuno; I 100) exit (- 1); return result;}

Create a main.c file as follows:

# include # include int main (void) {int xboarprintf ("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 named main

Gcc-o main sum.o main.o

Executive program

. / main

The execution result is the same as above.

3 using dynamic link library

Generate dynamic link library

Gcc sum.o-shared-o sum.so

Generate an executable file named main

Gcc-o main sum.o main.o

Execution

. / main

If the following error is reported, the newly generated sum.so was not found under 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 to find the 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 .so dynamic link library

Create a test.py file as follows:

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

Execution

Root@ubuntu:/ybg/python# python test.py so.sum (50) = 1275 the method of compiling and executing c program under Linux environment is shared here. I hope the above content can be helpful to everyone and learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: File content dynamic link generate compile environment program editor method more article result path good practical again single variable command Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple macOS Huawei Shulou Information OPPO Reno