Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify what function to export from .so library, when compiling the C code?

Tags:

c

I have a number of function in my "C" code. When I compile .so, I see all names in result .so file. How can I specify (in code or in make file) that only some functions should be exported, where as others are private just for internal use.

like image 224
alex2k8 Avatar asked Nov 27 '22 15:11

alex2k8


2 Answers

Since you mention .so files, it seems like a reasonable assumption that you're using gcc or a gcc-alike compiler.

By default all extern functions are visible in the linked object. You can hide functions (and global variables) on a case-by-case basis using the hidden attribute (while keeping them extern, which allows them to be used from other source files in the same library):

int __attribute__((visibility("hidden"))) foo(void)
{
    return 10;
}

Alternatively you can change the default to hidden by passing the -fvisibility=hidden option to gcc at compile time. You can then mark particular functions for export using:

__attribute__((visibility("default")))
like image 93
caf Avatar answered Feb 22 '23 23:02

caf


In C, if you want a function to remain internal to the file (technically, the "compilation unit") that contains it, you declare it "static". For example,

static int privateAddOne(int x) { return x + 1; }
like image 43
David Gelhar Avatar answered Feb 22 '23 22:02

David Gelhar