Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With GCC, how do I export only certain functions in a static library?

Tags:

c

static

I've created a static library in GCC, but I'd like to hide most of the symbols.

For example, test1.c:

extern void test2(void);
void test1(void) {
  printf("test1: ");
  test2();
}

test2.c:

extern void test1(void);
void test2(void) {
  printf("test2\n");
}

library_api.c:

extern void test1(void);
extern void test2(void);
void library_api(void) {
  test1();
  test2();
}

Now compile with:

gcc -c test1.c -o test1.o
gcc -c test2.c -o test2.o
gcc -c library_api.c -o library_api.o
ar rcs libapi.a test1.o test2.o library_api.o

How do I get only the "library_api()" function to show up for:

nm libapi.a

instead of the functions "test1()", "test2()", and "library_api()"? In other words, how do I hide "test1()" and "test2()" from showing up and being callable to external users of libapi.a? I don't want external users to know anything about internal test functions.

like image 926
Will Avatar asked Oct 01 '09 20:10

Will


2 Answers

The simplest solution is to #include test1.c and test2.c into library_api.c, and only compile that file. Then you can make test1() and test2() static.

Alternatively, you can combine the object files with ld -r, and use objcopy --localize-symbols to make the test functions static after linking. As this can get fairly tedious, I really recommend the first option, though.

like image 149
Martin v. Löwis Avatar answered Oct 11 '22 16:10

Martin v. Löwis


ld has the option

--retain-symbols-file FILE Keep only symbols listed in FILE

to allow you to explicitly name the symbols you want to keep.

like image 31
themis Avatar answered Oct 11 '22 16:10

themis