Implementing stub function and linking it to a definition in a library during run time

Atul Pant 1 Reputation point
2021-05-04T18:51:13.663+00:00

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?

Developer technologies C++
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. RLWA32 49,536 Reputation points
    2021-05-04T19:57:31.197+00:00

    If you use load-time-dynamic-linking when building your executable the linker will take as an input a DLL's import library to resolve references to functions that were imported from that DLL. There would be no need for you to write your own stub function.

    Why would you want to write your own stub?


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.