I just have an interesting idea. I was using objdump to dump a simple binary and I see many functions in the binary. Is it possible to create another C program that link with these functions? Assuming I know the parameters for input and output.
Some more information:
file1:test.c
#include <stdio.h>
int add(int x,int y)
{
return x+y;
}
int main(int argc, const char *argv[])
{
printf("%d\n",add(3,4));
return 0;
}
file2: test1.c
#include <stdio.h>
int main(int argc, const char *argv[])
{
printf("%d\n",add(8,8));
return 0;
}
gcc test.c -o test.exe
gcc test1.c test.exe -o test1.exe
Output:
ld: in test.exe, can't link with a main executable
collect2: ld returned 1 exit status
From a practical standpoint, there is little difference between an object (.o) file and an executable. The object file can contain unbound symbols, where the executable cannot. The executable must contain an entry point, where the object file has no such restriction. The executable has a more complete header. The executable also has all its jump offsets resolved, as it has been through the linking resolution phase. Some functions may have been permanently inlined away.
So yes, in theory you can create an executable which calls the functions from another executable, but not just with a normal link line. Your primary issue is that the second executable can’t have an entry point – a
mainfunction – and still be linked with the original (since the names would collide).If your goal is just to call the original functions, I suggest using a different method from the direct linking you seem to be suggesting. If you craft a shared library and put it in the LD_PRELOAD environment variable, and then invoke the original executable, you may use your library to effectively hook the program entry (possibly via the
_mainsymbol) and then call an alternate program routine. Because this library is loaded along with the original binary, you may call all the original functions…But the easiest way by far to call the functions from the binary is just to link with the object files instead of the executable.