I am creating a shared library in C but don't know what is the correct implementation of the source codes.
I want to create an API like for example, printHello,
int printHello( char * text );
This printHello function will call another function:
In source file, libprinthello.c,
void printHello( char * text )
{
printHi();
printf("%s", text);
}
Since this printHello function is the interface for the user or application:
In header file libprinthello.h,
extern void printHello( char * text);
Then in the source file of the printHi function, printhi.c
void printHi()
{
printf("Hi\n");
}
Then my problem is, since printHello is the only function that I want to expose in the user, what implementation should I do in printHi function?
Should I also extern the declaration of the printHi function?
You can use two separate header files:
In libprinthello.h:
#ifndef LIBPRINTHELLO_H /* These are include guards */
#define LIBPRINTHELLO_H
void printHello(char * text);
#endif
In libprinthi.h:
#ifndef LIBPRINTHI_H
#define LIBPRINTHI_H
void printHi();
#endif
In libprinthello.c:
#include "libprinthi.h"
#include "libprinthello.h"
void printHello(char * text)
{
printHi();
printf("%s", text);
}
In libprinthi.c:
#include "libprinthi.h"
void printHi()
{
printf("Hi\n");
}
Then the user code includes only libprinthello.h, and you keep libprinthi.h away from the user, making printHi() invisible to them (the user code would also link against the shared library):
#include "libprinthello.h"
int main()
{
printHello("Hello World!\n");
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With