2

这是我第一次测试 C 程序。我有这个我想测试的头文件:

#ifndef CALCULATOR_HELPER_H
#define CALCULATOR_HELPER_H
#endif

    int add(int num1, int num2) {
        return num1 + num2;
    }

我正在使用框架 CUnit 来测试它。我正在使用 Netbeans 作为 IDE。以下是代码。

#include <stdio.h>
#include <stdlib.h>
#include "CUnit/Basic.h"
#include "calculator_helper.h"

/*
 * CUnit Test Suite
 */

int init_suite(void) {
    return 0;
}

int clean_suite(void) {
    return 0;
}

/* IMPORTANT PART: */

void testAdd() {
    int num1 = 2;
    int num2 = 2;
    int result = add(num1, num2);
    if (result == 4) {
        CU_ASSERT(0);
    }
}

int main() {
    CU_pSuite pSuite = NULL;

    /* Initialize the CUnit test registry */
    if (CUE_SUCCESS != CU_initialize_registry())
        return CU_get_error();

    /* Add a suite to the registry */
    pSuite = CU_add_suite("newcunittest", init_suite, clean_suite);
    if (NULL == pSuite) {
        CU_cleanup_registry();
        return CU_get_error();
    }

    /* Add the tests to the suite */
    if ((NULL == CU_add_test(pSuite, "testAdd", testAdd))) {
        CU_cleanup_registry();
        return CU_get_error();
    }

    /* Run all tests using the CUnit Basic interface */
    CU_basic_set_mode(CU_BRM_VERBOSE);
    CU_basic_run_tests();
    CU_cleanup_registry();
    return CU_get_error();
}

问题

当我构建测试时,我得到了 BUILD TESTS FAILED。更具体地说,我明白了:

在函数“添加”中:NetBeans/Calculator/calculator_helper.h:12:
'add' 的多重定义
构建/调试/GNU-Linux-x86/tests/tests/newcunittest.o:NetBeans/Calculator/./calculator_helper.h:12:
首先在这里定义 collect2: error: ld returned 1 exit status

谁能告诉我为什么我会收到这个错误。我尝试在谷歌上搜索,但没有找到运气。

4

3 回答 3

2

我有这个我想测试的头文件:

您正在头文件中定义一个函数:

int add(int num1, int num2) {
    return num1 + num2;
}

在标题中声明它:

#ifndef CALCULATOR_HELPER_H
#define CALCULATOR_HELPER_H

int add(int num1, int num2);

#endif      /* the endif goes at the end of the file */

...并在源文件中定义它:

#include "helper.h"

int add(int num1, int num2) {
    return num1 + num2;
}

推荐阅读:

于 2013-03-01T12:39:59.483 回答
1

这:

#ifndef CALCULATOR_HELPER_H
#define CALCULATOR_HELPER_H
#endif

是一个“包含守卫”。但它做错了:你的代码应该在#endif 之前,而不是之后。

额外提示:不要在代码中使用“助手”这个词——总有一个更好的。就像在这种情况下,您可以调用它CALCULATOR_MATH_H

于 2013-03-01T12:37:58.040 回答
1

链接器告诉您“添加”有两种定义。忽略其他回复提出的有效点一分钟,您的代码构建良好,因为它在 Ubuntu 12.04.2 上使用 gcc 在命令行上。我这样构建它并没有看到任何警告(已将 libcunit.a 安装到 /usr/local/lib):

gcc -Wall -c testsuite.c
gcc testsuite.o -L/usr/local/lib -lcunit -static -o testsuite

它运行了,正如你所期望的那样失败:

...
Suite: newcunittest
  Test: testAdd ...FAILED
    1. testsuite.c:25  - 0
...

在这种情况下,您的问题似乎是由 Netbeans 中的某些东西也定义了“添加”函数引起的,或者您的构建内容比您发布的更多,其他文件包括“calculator_helper.h”,这将导致您的函数被由于其损坏的包含保护,包含并定义了两次。

您可能还想更改测试的样式,以便它断言它期望为真。当 add() 做正确的事情时,您当前的测试未通过断言,这不是大多数人所期望的!试试这个:

void testAdd() {
    int num1 = 2;
    int num2 = 2;
    int result = add(num1, num2);
    CU_ASSERT(result == 4);
}
于 2013-03-15T16:26:20.723 回答