c - 如何构建灵活的代码层次结构

标签 c algorithm makefile flexibility

因此,我有一个算法,由参数 A、B、C 和 D 以及操作 X、Y 和 Z 组成。目标是编写代码来测试 A、B 的所有组合(在一定范围内) , C 和 D, 并可能改变操作 X, Y 或 Z.

如果只是将变量放在某个范围内,这会很简单。但由于我还想更改运算符,所以它并不那么简单。

我的想法是编写涵盖所有组合的代码。例如,假设只有两个参数(A 和 B),并且两者的范围相同:[1,2],整数。该代码将构建(如果可能,执行)4 个不同的可执行文件,对应于将算法用于:

A = 1, B = 1
A = 1, B = 2
A = 2, B = 1
A = 2, B = 2

现在添加运算符。例如,我们选择前面的示例并添加操作 X,其中它可以是 [+,-]。结果集是:

A = 1, B = 1, X = +
A = 1, B = 2, X = -
A = 2, B = 1, X = +
A = 2, B = 2, X = -
A = 1, B = 1, X = -
A = 1, B = 2, X = +
A = 2, B = 1, X = -
A = 2, B = 2, X = +

(我希望我写了所有的组合)

无论如何,我相信可以使用 makefile 构建这样的结构,其中它将值归因于用 C 编写的代码的常量。我不确定是否可以通过这种方式更改运算符。为了简单起见,我正在考虑使用 makefile。总是可以编写生成代码的代码,但对于这种情况似乎有些夸张。

也许它会创建一个树结构?我不确定拥有(并选择第一个示例)是否有益:

|--Makefile
|--A1
|   |--B1
|   |   |--a.out
|   |--B2
|       |--a.out
|--A2
    |--B1
    |  |--a.out
    |--B2
        |--a.out

使用 make 我相信我可以向代码添加额外的变量/运算符并轻松地重建所有测试。此外,此结构是否允许使用 make 的作业功能来运行多个线程?

谢谢

最佳答案

我以前用过的方法:

您可以编写一个 shell 脚本来定义一个宏,然后编译该程序。使用这种方法,您可以只编写一个源文件并编译多个程序。对通过命令行参数传入的两个数字执行某些操作的示例程序:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv[]){
    if (argc != 3){ //takes just 2 numbers (for example purposes)
        fprintf(stderr, "Usage: prog num1 num2\n");
        return 1;
    }
    int a = (int)strtol(argv[1], (char**)NULL, 10);
    int b = (int)strtol(argv[2], (char**)NULL, 10);
    int c = a MySpecialOperation b;
    printf("%d %s %d = %d\n", a, MySpecialOperationText, b, c);
    return 0;
}

您很快就会注意到 MySpecialOperationMySpecialOperationText 是未定义的。这是故意的。 (该程序还假定命令行参数有效。)

现在假设您需要 4 个程序来执行 4 种基本算术运算。编写脚本来编译您的程序(这是在 BASh 中):

echo \#define MySpecialOperation \+ > tmp.c
echo \#define MySpecialOperationText \"plus\" >> tmp.c
cat myprogram.c >> tmp.c
gcc tmp.c -o addition_prog
echo \#define MySpecialOperation \- > tmp.c
echo \#define MySpecialOperationText \"minus\" >> tmp.c
cat myprogram.c >> tmp.c
gcc tmp.c -o subtraction_prog
echo \#define MySpecialOperation \* > tmp.c
echo \#define MySpecialOperationText \"times\" >> tmp.c
cat myprogram.c >> tmp.c
gcc tmp.c -o multiplication_prog
echo \#define MySpecialOperation \/ > tmp.c
echo \#define MySpecialOperationText \"divided by\" >> tmp.c
cat myprogram.c >> tmp.c
gcc tmp.c -o division_prog
rm tmp.c

此脚本自动创建一个新文件,向其写入预处理程序语句#define,定义先前 undefined variable ,然后将原始源文件附加到其中。现在,编译器会将 MySpecialOperation 替换为操作 (+-*/) 和 MySpecialOperationText 加上适当的词,代码将编译并执行该操作。

关于c - 如何构建灵活的代码层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33300839/

相关文章:

c - TreeView 更改项目图像的颜色

c - 在 C 中映射非顺序值的最佳方法

c++ - C++ 中的图形表示

C++ makefile 未创建必要的 .o 文件

c - 使用 -g 在 ArchLinux 中找不到调试符号

c - 结构声明中的多个变量

c++ - 这是 C/C++ 中的未定义行为吗(第 2 部分)

c++ - 在 C++ 中转换树

javascript - JS Array NEQ 操作的最佳性能操作

makefile - 参数化 Makefile 目标