user5054 user5054 - 2 months ago 12
C Question

Creating a shared object from C code for R

I have a C code and I want to call the functions in it from R by creating a shared object and dynamically loading that object in R. The code to create a shared object in R is:

R CMD SHLIB myfile.c


And the general way is:

gcc -c -Wall -Werror -fpic myfile.c
gcc -shared -o myfile.so myfile.o


I am wondering whether there is any difference between the two
myfile.so
files created by those different pieces of code in terms of usage in R. The sizes of the two files are quite different (17KB and 32 KB), which confused me.

Answer

When you do

gcc -c -Wall -Werror -fpic myfile.c
gcc -shared -o myfile.so myfile.o

you miss several flags that R CMD SHLIB takes, like optimization flag -O2, debugging flag -g, etc. Why not have a look at what is printed to the screen when you do:

R CMD SHLIB myfile.c

Flags I have mentioned have influence on code size, as well as efficiency of your compiled code. The resulting object code is different. You can use disassembler:

objdump -d myfile.so

to check (binary) assembly code as well as code size. You can also use

gcc -S -Wall -Werror -fpic myfile.c

to check (readable) assembly code. You will see huge difference whether you use -O2 or not.


Godbolt compiler explore is a GUI interactive assembler. You type in C code on the left-side window, then choose compiler, compilation flags, output display configuration, etc, then the assembly code will be produced on the right-side window. This is super convenient for HPC code writers to evaluate and optimize their code. For you, this is a handy approach to compare the difference in object code.