我写了一个程序,我想把它链接到另一个 C 程序。从某种意义上说,通过使用 include 或任何其他指令,我需要链接程序,以便后者可以调用前者的函数。我怎样才能在代码块中完成这个?
最佳答案
假设您现在有两个程序 A 和 B。在 A 中您有函数 c
。因此,将 c
移动到单独的文件 c.c
并生成 c.h
文件,它可以作为 #include 包含在 A 和 B 程序中“c.h”
。比独立编译A和B。
这将是最简单的方法。
编辑:
所有相互使用的函数都应该在“库”中。例如:
// c.h
int c(int x1, int x2); // this will be called from outside
extern int callCount; // to be available outside
和
// c.c
#include "c.h"
int d(int x); // this cannot be called from outside
// global variable to count calls of c function
int callCount = 0;
int c(int x1, int x2)
{
callCount++; // changing of global variable
return (x1 + x2) * d(x1);
}
int d(int x)
{
return x * x;
}
和用法
// prog A
#include <stdio.h>
#include "c.h"
int main(void)
{
int a = 1, b = 2;
printf("c = %d\n", c(a, b));
printf("c = %d\n", c(2*a, b - 1));
printf("Function c was called %d times\n", callCount);
return 0;
}
您计划从其他文件调用的所有函数都应在 h 文件中声明。这是常用的方法,但也可以在网上找到很多技巧,例如static
函数、#define
侦探和条件编译等。
关于c - 在另一个程序中加载一个 c 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28803776/