简体   繁体   English

组合(链接)2个c程序

[英]Combining (linking) 2 c programs

I have program_1.c我有 program_1.c

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

program1_foo.c 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现在我有第二个程序 program_2.c

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

program2_foo.c 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?这显然是一个最小化的问题,但我想将 2 个单独的程序编译成一个程序,并调用第一个程序的主程序,而程序 1 的函数和定义不会泄漏到程序 2 中。实现的最佳方法是什么这个?

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.编辑:裸机嵌入 c,因此可以通过设置堆栈指针在程序之间跳转,但如果可能,这是我想避免的。

building a static library but only exposing prog1_main() would be an ideal solution, but it appears this is not possible with c.构建一个静态库但只公开 prog1_main() 将是一个理想的解决方案,但似乎这对 c 来说是不可能的。

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 的模块编写包装器:

// 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM