scao
scao

Reputation: 11

Combining (linking) 2 c programs

I have program_1.c

void foo(void);
int main(void)
{
   foo();
}

program1_foo.c

void foo(void)
{
    do_program1_things();
}

This is normally compiled into its own program.

Now I have a second program program_2.c

void foo(void)
int main(void)
{
   foo();
   program1_main();
}

program2_foo.c

void foo(void)
{
    do_program2_things();
}

this is obviously a minimalised problem, but I want to compile 2 seperate programs into a single program, and invoke the main of the first program, without having functions and definitions of program 1 leaking into program 2. What would be the best method to achieve this?

Edit: bare metal embedded c, so it would be possible to jump between programs by setting stack pointer, but that's something i want to avoid if possible.

building a static library but only exposing prog1_main() would be an ideal solution, but it appears this is not possible with c.

Upvotes: 1

Views: 45

Answers (1)

the busybee
the busybee

Reputation: 12590

You understood the problem: symbols like function names that need to be linked between separate translation units have to be public. You cannot have two different symbols of the same name. So you need to differentiate them somehow.


Disclaimer: This is just one possibility, and a quite primitive one.

You can write wrappers for the modules of program1 like this:

// program1_main.c
#define foo program1_foo
#define main program1_main
#include "program_1.c"
// program1_foo.c
#define foo program1_foo
#include "program1_foo.c"

Upvotes: 1

Related Questions