When I was reading about using shared libraries, I learnt how the definitions of standard C functions, like printf, are resolved during run-time. I want to implement functions in my project in the similar manner. I can have stub definition of functions for compiling and linking phase. And actual definition of the functions will be present in a library on the device where I'll run my executable.
Suppose I have a main function:
include<stdio.h>
include"sum.h"
int main()
{
int num = 10;
int result = 0;
result = sum(num);
printf("Sum = %d\n",result);
return 0;
}
And my sum.h looks like:
ifndef SUM_H
define SUM_H
ifdef __cplusplus
extern "C" {
endif
ifndef __EXPORT
ifdef _USERDLL
define __EXPORT __declspec(dllexport)
else
define __EXPORT __declspec(dllimport)
endif // _USER_DLL
endif // __EXPORT
__EXPORT int sum(int num);
}
endif
endif
And while builiding this executable, I'll use stub definition in sum_stub.c file:
// sum_stub.c
include<stdio.h>
include"sum.h"
int sum(int num) {
int res = 0;
printf("Inside stubbed function. Result=%d\n",res);
return res;
}
Let the executable that is build using above files is get_sum.exe
The actual function that will calculate sum is compiled as a shared library, say sum.dll.
// sum.c that will be compiled to sum.dll
include<stdio.h>
include"sum.h"
int sum(int num) {
int res = 0;
int i=0;
for (i=0; i<num; i++)
res = res + i;
return res;
}
Now as I run my executable, get_sum.exe, how can I link sum.dll at runtime so that correct function definition is used (inside sum.dll) instead of the stubbed one, that I used while compiling the executable?