运行 几个 C 文件的自动化测试

Running automated tests on several C files

我在结构中有几个文件

/algorithms
    /a1
        a1.c
    /a2
        a2.c
    /a3
        a3.c

这些文件中的每一个都包含一个同名函数。除了名称(与文件名相同)外,每个文件都具有相同的签名。从本质上讲,每种算法都是对同一事物的不同实现——以不同的方式达到相同的目的。但是可能会有一些小的辅助函数。

文件的内容(评论、功能、布局等)不能更改。 我想创建一些方法来测试每个算法。此方法 仅限于在 C 中实现。

我有一个主要包含三个函数的 C 文件:

// Runs the algorithm, which modifies the given integer array.
void run(void (*algorithm) (int*, size_t));

// Checks that the algorithm successfully completed and
// the array is correct.
int check(int*, size_t);

// Should call run() with appropriate algorithm and a random data set
// and then call check() to make sure it worked.
int main(int, char**);

我需要一种自动包含适当文件然后调用的方法 它们内部的功能。目前,我有一个获取所有算法的 bash 文件,复制测试文件,在开头添加一个 #include 语句和一个生成的 injected_main() 函数,该函数由实际 main() 函数。它 运行 复制了测试仪,然后将其删除。

function testC() {

    local tempout=temptest.c
    local filename="$(basename -- )"
    local functionname="${filename%.*}"
    local main="void injectedMain() {test(&$functionname);}"
    local include="#include\"\"\n$main"

    touch $tempout
    chmod +x $tempout
    printf "$filename: "
    cp $TESTER_C $tempout
    printf "$include" >> $tempout
    gcc $tempout -o tempout -Wall -Wextra -pedantic
    ./tempout
    rm $tempout tempout

}

函数在每个算法 C 文件的循环中 运行。 然而,这种方法容易出错,不可扩展,而且非常丑陋。有更好的方法吗?

你不能只 header 包括你的算法实现并遍历所有这些吗?

类似于

#include "a1/a1.h"
#include "a2/a2.h"
#include "a3/a3.h"

typedef void (*AlgorithmImplemetation)(void); //Your algorithm function signature goes here

AlgorithmImplemetation *all = {
    a1,
    a2,
    a3
};

然后将此 header 包含在您的 main.c 中并循环遍历 all

结合您现有的代码和@Herve 的回答。

您可以让 bash 脚本只收集所有算法并构建一个像 @Herve 提议的那样的 C 源代码。这样就不会有容易出错的手动步骤。

为了 运行 所有测试都会编译这个自动生成的源代码,并 link 它到你的测试 运行ner。让后者循环遍历all.