c++ - 把 main 放在哪里,在那里写什么?

标签 c++ program-entry-point

我在文件 tested.cpp 中有以下代码:

#include <iostream>
using namespace std;

class tested {
    private:
        int x;
    public:
        tested(int x_inp) {
            x = x_inp;
        }

        int getValue() {
            return x;
        }
};

我还有另一个文件(名为testing.cpp):

#include <cppunit/extensions/HelperMacros.h>
#include "tested.cpp"

class TestTested : public CppUnit::TestFixture
{
    CPPUNIT_TEST_SUITE(TestTested);
    CPPUNIT_TEST(check_value);
    CPPUNIT_TEST_SUITE_END();

    public:
        void check_value();
};

CPPUNIT_TEST_SUITE_REGISTRATION(TestTested);

void TestTested::check_value() {
    tested t(3);
    int expected_val = t.getValue();
    CPPUNIT_ASSERT_EQUAL(7, expected_val);
}

当我尝试编译 testing.cpp 文件时,我得到:undefined reference tomain'`。嗯,这是因为我没有 main(程序的入口点)。因此,编译器不知道如何开始执行代码。

但我不清楚的是如何执行testing.cpp中的代码。我尝试添加:

int main() {
        TestTested t();
        return 1;
}

但是,它不会打印任何内容(并且预计会返回一条错误消息,因为 3 不等于 7)。

有人知道运行单元测试的正确方法是什么吗?

最佳答案

既然您正在编写 cppunit 测试,为什么不查看 cppunit 文档? ( http://cppunit.sourceforge.net/doc/lastest/cppunit_cookbook.html )

它告诉你主要灵魂是这样写的:

#include <cppunit/ui/text/TestRunner.h>
#include "ExampleTestCase.h"
#include "ComplexNumberTest.h"

int main( int argc, char **argv) {
  CppUnit::TextUi::TestRunner runner;
  runner.addTest( ExampleTestCase::suite() );
  runner.addTest( ComplexNumberTest::suite() );
  runner.run();
  return 0;
} 

关于c++ - 把 main 放在哪里,在那里写什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16077987/

相关文章:

c++ - 混合 C 和 C++ 导致异常终止

c++ - 如何隔离arm设备上的故障?

java - 主类中的变量

c++ - BinarySearch 返回它所属位置的索引

c++ - g++ 在终端中,构建有效但没有 a.out

java - 为什么包含主要方法的类没有实例化并且在Java中仍然可以?

c++ - C++ 不将 `std::vector<std::string>` "overload"作为参数添加到 `main()` 的原因是什么?

java - Android 应用程序一开始就崩溃

c++ - 从类中的 main 调用函数

python - 正则表达式在 C++ 中不匹配?