How can I create a function with an internal library?

For example, if I have two files, foo.cand bar.o, a foo.ccontains a function foo()that refers to a function bar()in bar.o:

int foo(int x) { x = bar(x); /* ... */ }

How can I compile a static or dynamic library that provides foo()but does not expose bar()? In other words, I want to bar()communicate only inside the library.

+4
source share
2 answers

C , , " ". bar() foo.c static. , #include foo.c ( bar.o)...

, C, . , GCC clang ( , ) , : __attribute__ ((visibility ("hidden"))) - -fvisibility=hidden , , bar.c.

C

C, C bar() static bar.c foo() , , struct, ( "private"), struct , .

:

bar.h (, ):

struct bar_private_struct { int (*bar)(int); };
extern struct bar_private_struct *bar_functions;

bar.c:

#include "bar.h"
static int bar (int x) { /* … */ return x; }
static struct bar_private_struct functions = { bar };
struct bar_private_struct *bar_functions = &functions;

foo.c:

#include "bar.h"
int foo (int x) { x = bar_functions->bar(x); /* … */ }

bar_functions, / . bar.h , "private". "private" , .

, :

GNU ld script, libfoobar.version:

FOOBAR {
    global: *;
    local: bar;
};

gcc:

gcc -shared -o libfoobar.so foo.o bar.o -Wl,-version-script=libfoobar.version

clang ld ( OS X) , unexported ( ):

_bar

clang:

clang -shared -o libfoobar.dylib foo.o bar.o -Wl,-unexported_symbols_list,unexported

bar , foo ( bar), ( ) .

, foo.c:

int bar(int x);
int foo (int x) { return bar(x) * 3; }

bar.c:

int bar (int x) { return x * 2; }

main.c ( bar):

#include <stdio.h>
int foo(int x);
int bar(int x);
int main () {
    (void) printf("foo(2) = %d\n", foo(2));
    (void) printf("bar(2) = %d\n", bar(2));
    return 0;
}

:

# before unexporting bar:
$ nm -gU libfoobar.dylib
0000000000000f70 T _bar
0000000000000f50 T _foo
$ ./main
foo(2) = 12
bar(2) = 4

# after unexporting bar:
$ nm -gU libfoobar.dylib
0000000000000f50 T _foo
$ ./main
foo(2) = 12
dyld: lazy symbol binding failed: Symbol not found: _bar
+7

.

, , .

, , , .

0

All Articles