我已经创建了一个小程序来镜像我的源代码在这里,main在调试模式下,在运行主应用程序之前调用外部库测试程序函数想象一下库中的构造函数分配内存,在调试时也测试一些静态函数如果测试了该库,它将运行静态测试程序代码如果使用了该库,则使用静态测试程序代码静态测试程序在每次调用库函数时运行。
主C

// calls test and library
#include <stdio.h>
#include <stdlib.h>

// to test if the lib is there and the function does what it says claims
extern int testExternalLibFunctions(void);

#include "lib.h"

int main(){
    testExternalLibFunctions();

    printf("main function uses doTheTango\n");
    doTheTango();

    // do the magic stuff here and
    doTheTango();

    return 0;
}

测试库c
 #include <stdio.h>
 #include "lib.h"

static int Static_doTheTangoTest();

int testExternalLibFunctions(){
    // define DO_THE_TANGO_TEST_SELF_TRUE
    Static_doTheTangoTest();
    // undefine DO_THE_TANGO_TEST_SELF_TRUE
    return 0;
}

int Static_doTheTangoTest(){
    printf("external function tester calls doTheTango\n");
    doTheTango();
    return 0;
}

图书馆
#ifndef DO_THE_TANGO_HEADER
#define DO_THE_TANGO_HEADER

extern int doTheTango();

#endif // DO_THE_TANGO_HEADER

库c
#include <stdio.h>
#include <assert.h>
#include "lib.h" //self
// ONLY HERE SHOULD STATIC FUNCTIONS BE TESTED

static int STATIC_TEST();

int doTheTango(){
    printf("Dancing is fun - ");
    // if defined DO_THE_TANGO_TEST_SELF_TRUE
    STATIC_TEST();
    // endif
    getchar();
    return 0;
}
int STATIC_TEST(){
    printf("Static test 1, Yet again!");
    return 0;
}

这并不是要分割测试人员和主功能,因为主功能正在调用更多的测试人员等他们是相互依赖的!
如何使库仅在首次包含时执行静态测试类似于在python中测试
if(__name__ == __main__) -> do the static tests

最佳答案

我不知道你想干什么我从源代码中看到你说“静态测试1,再一次!”,所以我假设您不希望在对doTheTango的后续调用中调用STATIC_测试。
如果这是你想要的,那么:

int doTheTango(){
    static int isTested = 0;
    printf("Dancing is fun - ");
    if (!isTested) {
        isTested = 1;
        STATIC_TEST();
    }
    getchar();
    return 0;
}

关于c - 调用C静态测试的构造,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33317615/

10-11 22:50
查看更多