【问题标题】:How to solve redefinition of main in makefile如何解决makefile中main的重新定义
【发布时间】:2018-02-05 14:42:53
【问题描述】:

我正在尝试使用 makefile 将三个文件编译并链接到可执行文件中,但似乎重新定义了 main 或以某种方式弄乱了编译/链接过程。该项目是针对一个类,目标是实现一个线性反馈移位寄存器,但我们必须使用一个makefile。

我在哪里重新定义了 main?如何更改我的 makefile 以创建我的可执行文件?我注意到 test.o 的错误点是重新定义了 main,但我不确定为什么或如何。

错误:

g++ -c main.cpp LFSR.cpp -Wall -Werror -ansi -pedantic
g++ -c test.cpp -Wall -Werror -ansi -pedantic
g++ main.o LFSR.o test.o -o ps2a -lboost_unit_test_framework
test.o: In function `main':
test.cpp:(.text+0xa3): multiple definition of `main'
main.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
Makefile:4: recipe for target 'ps2a' failed
make: *** [ps2a] Error 1

我的生成文件:

all: ps2a

ps2a: main.o LFSR.o test.o
     g++ main.o LFSR.o test.o -o ps2a -lboost_unit_test_framework

LFSR.o: LFSR.cpp LFSR.hpp
     g++ -c LFSR.cpp -Wall -Werror -ansi -pedantic

main.o: main.cpp LFSR.hpp
    g++ -c main.cpp LFSR.cpp -Wall -Werror -ansi -pedantic

test.o: test.cpp
    g++ -c test.cpp -Wall -Werror -ansi -pedantic

clean:
    rm *.o ps2a

main.cpp:

#include "LFSR.hpp"

int main(){
}

LFSR.hpp

#include <string>
#include <iostream>

class LFSR{
public:
    LFSR(std::string, int);
    int step();
    int generate(int k);
private:
    std::string bitString;
    int tapPos;
};

LFSR.cpp:

#include "LFSR.hpp"

void makeBitStringValid(std::string& str);

LFSR::LFSR(std::string str, int t){
}

int LFSR::step(){
    return 0;
}

int LFSR::generate(int k){
    return 0;
}

void makeBitStringValid(std::string& str){
}

test.cpp(注意,这是导师给出的——我还不完全确定它是如何工作的)

#include <iostream>
#include <string>

#include "LFSR.hpp"

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE(fiveBitsTapAtTwo) {

  LFSR l("00111", 2);
  BOOST_REQUIRE(l.step() == 1);
  BOOST_REQUIRE(l.step() == 1);
  BOOST_REQUIRE(l.step() == 0);
  BOOST_REQUIRE(l.step() == 0);
  BOOST_REQUIRE(l.step() == 0);
  BOOST_REQUIRE(l.step() == 1);
  BOOST_REQUIRE(l.step() == 1);
  BOOST_REQUIRE(l.step() == 0);

  LFSR l2("00111", 2);
  BOOST_REQUIRE(l2.generate(8) == 198);
}

【问题讨论】:

  • 不要写 main.cpp。
  • 为什么我不应该写 main.cpp?
  • 因为你已经有了main函数?
  • 因为你有两次 main 定义。它已经在 test.cpp 中了。

标签: c++ makefile


【解决方案1】:

不要提供自己的 main,因为 Boost 单元测试框架已经在您的 test.cpp 中提供了一个:

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>

Dynamic library variant of the UTF

与静态库变体函数不同,main() 不能驻留在 动态库体。相反,此变体提供默认功能 main() 实现作为标题的一部分 boost/test/unit_test.hpp 作为测试文件主体的一部分生成。函数 main() 是 仅在 BOOST_TEST_MAIN 或 BOOST_TEST_MODULE 时生成 标志是在测试模块编译期间定义的。对于单文件 测试模块标志可以在测试模块的 makefile 中定义,或者 在标题 boost/test/unit_test.hpp 包含之前。对于多文件 测试模块标志不能在 makefile 中定义,必须定义 只在一个测试文件中,以避免重复的副本 函数 main()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多