Friday, September 4, 2020

Cross compiling a C project for raspberry pi

 Developing an application for Rapsberry pi can be done using Python, QT or C or C++.  Only thing to keep in mind while compiling is to cross compile the C and C++ files for ARM architecture. For this you can change the make file and set the ARM compiler path for compiling the files.  Problem arises when you are developing a project in Python and want to use C code along with it. This is not a tough task to achieve but tricky one to do so. You can call C function from python in two ways. You can create a wrapper of the C function that you want to use in python.  To know more about wrappers you can visit this page or google it. Second option is to create a shared library(.so file)  and use the function with the help of ctypes.  If you have more than number of  C files and the files calls functions of other C files, I will prefer to use ctypes after creating a shared object file. Here I will explain how to cross compile C files to create a shared object and how to call functions of the shared object using ctypes.

In my Ubuntu 16.04 I had given the following command to compile my C files to create a shared object.

gcc - fpic -shared -o <Name of .so file>  <Name of C files with path>

Example : I have to create a shared object library having some math functions and string functions, the final command for creating the shared object library will be

gcc – fpic – shared – o utility.so utility_main.c  mathUtil/mathfunc.c  stringUtil/stringfun.c   

You can have all your C file separated by space

This will create utility.so file which can be used in my python code using ctypes. If you want to use your python code in Raspberry pi or any other ARM architecture device you need to cross compile the library using the ARM cross compiler. In my case I am using Raspberry pi 3B and my cross compiler is arm-linux-gnueabihf-gcc. So I will just change the compiler in the above command to cross compile my application for ARM architecture. You can use your cross compiler.

Here is my command for cross compiling utility.so shown above.

arm-linux-gnueabihf-gcc  -fpic -shared -o utility.so utility_main.c  mathUtil/mathfunc.c  stringUtil/stringfun.c  

Now you can copy this .so file to your python project.  In your python file add “import ctypes” in the top where all import files are called. Then create object of the shared object and call the function you want to use in your Python module

Example : If I have to call addNumber function my utility shared object in my python file I have to do the following steps.

1.       Import ctypes

2.           obj = ctypes.CDLL(utility.so')

3.           z = obj.addNumber(24,35)

No comments:

Post a Comment