Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared library in C

Tags:

c

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?

like image 909
domlao Avatar asked Nov 26 '25 21:11

domlao


1 Answers

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;
}
like image 169
In silico Avatar answered Nov 28 '25 17:11

In silico