너를 속였다
너를 속였다

Reputation: 1069

Prevent library user from overriding my function

I have create dynamic library in which I define a function. I use this function internally in my own library and dont expose via headers. But if user of my library defines similar function then that function overrides my function and breaks my lib.

Here is an example:

libmylib.so:

#include <stdio.h>

void hello() {
    puts("hello form t.c");
}

void hello1() {
    hello();
}

a.out:

#include <stdio.h>

void hello1();

void hello() {
    puts("hello from main.c");
}

int main() {
    hello();
    hello1();
}

Output I get:

hello from main.c
hello from main.c

Upvotes: 1

Views: 135

Answers (1)

yugr
yugr

Reputation: 21886

If function is local to a single a file just make it static. Otherwise you can hide it via

__attribute__((visibility("hidden")))
void hello() {
    puts("hello from main.c");
}

Actually the recommended approach is to hide all functions by default (by adding -fvisibility=hidden to CFLAGS) and only export functions that you need via __attribute__((visibility("default"))).

Upvotes: 2

Related Questions