CL So
CL So

Reputation: 3759

How to use two libraries if they have same function in C?

I found some discussion, the answer is using static, another answer is renaming the function

but, if I don't have source code, how can I rename the function?

I also tried the static, but not work, error: "warning #2135: Static 'func' is not referenced."

What is the correct solution?

main.c

#include <stdio.h>
#include "liba.h"
#include "libb.h"

int main(int argc, char *argv[])
{
    printf("Main\n");
    func();
    return 0;
}

liba.h

static void func(void);

liba.c

#include <stdio.h>
#include "liba.h"

static void func(void)
{
    printf("lib a\n");
}

libb.h

static void func(void);

libb.c

#include <stdio.h>
#include "libb.h"

static void func(void)
{
    printf("lib b\n");
}

Upvotes: 2

Views: 2760

Answers (3)

Deva
Deva

Reputation: 48

You can't do it as far as I know. I am not saying it is not possible, but impractical as 'c' doesn't allow polymorphism and namespaces. And yes the link shared by Jayesh is informative have a look What should I do if two libraries provide a function with the same name generating a conflict?

Upvotes: 0

Baldrick
Baldrick

Reputation: 11840

It can be done, but not directly. You need to abstract away the offending duplicate function behind a wrapper. As described by the answer here (linked by Jayesh):

If you don't control either of them you can wrap one of them up. That is compile another (statically linked!) library that does nothing except re-export all the symbols of the original except the offending one, which is reached through a wrapper with an alternate name.

Upvotes: 1

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28528

In C header file function are global and cause conflict if are of same name. You need to change the name to avoid conflict.

Upvotes: 1

Related Questions