Pryda
Pryda

Reputation: 1029

Call functions from outside a static library in C

I need to generate a static library MyLib.lib that contains unimplemented functions.

Inside the project, I called the unimplemented function as shown below:

/* Inside MyLib.c */

#include "MyLib.h"

void foo(void)
{
   func(); // To be implemented by the user.
}

And In the header file MyLib.h, I included a header file

#include "user.h" // contains user_imlplementation_of_func()

...


#define func()         user_imlplementation_of_func()

To make things simple, let's just give an example of the user.c:

void user_imlplementation_of_func(void)
{
   printf("OK");
}

I would like to know is it possible to do this call? Otherwise, Is there any other solution to use unimplemented functions inside a static library and let the user define them after compressing the project from a source code to a .lib file

Upvotes: 1

Views: 4266

Answers (2)

kalehmann
kalehmann

Reputation: 5031

You need to declare the unimplemented function as extern in the header of your library. This tells the compiler, that the function will be defined somewhere else.

Example:

MyLib.h

void foo();

extern void func();

MyLib.c

#include "MyLib.h"

void foo(void)
{
    func();
}

main.c

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

void func()
{
    printf("Hello, world!\n");
}

int main()
{
    foo();
}

Example build:

cc -o MyLib.o -c MyLib.c
cc -o out main.c MyLib.o

Output:

$ ./out
Hello, world!

However, for more readability I suggest you to pass your project functions as pointers to your library functions. This is commonly known as callback.

Example:

/* MyLib.c */

#include "MyLib.h"

void foo(void (*func)(void))
{
   func();
}

Now you can call the foo function in your project with:

foo(&user_imlplementation_of_func);

Edit:

As stated in the comments by the user theSealion a third solution is the usage of weak symbols. The wikipedia articel "Weak symbol" provides a good explanation with examples.

Upvotes: 3

Igor Galczak
Igor Galczak

Reputation: 142

You can do some else - function pointer:

//youLib.c

extern void (*func)(void) = NULL;

extern void foo()
{
    if (func != NULL) {
        func();
    }
}
//main.c

static void user_imlplementation_of_func(void)
{
    printf("Hello\n");
}

func = &user_imlplementation_of_func;
foo(); //Will printf "Hello"

Upvotes: 0

Related Questions