c - 在另一个程序中加载一个 c 程序

标签 c include codeblocks

我写了一个程序,我想把它链接到另一个 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/

相关文章:

c - stm32f103中多 channel 转换中adc的转换顺序

C Gameboy 独立函数和主文件

c++ - 为什么我可以在多个包含const int的cpp文件中包含一个头文件而不会出现编译错误?

c++ - 库包含具有相同标题名称的路径

c - 进程终止,状态为 -1073741819 在 C 中

c++ - 未定义的函数引用 "CashRegister::GetTotalPrice"

c++ - 处理浮点异常

c - Unix: "ls -l"在哪里获取设备大小字段中的逗号分隔值?

c - Visual Studio 2010 错误# U1095,NMAKE

c++ - QuickSort 不排序数组