对代码::块中另一个项目的函数的未定义引用

Undefined reference to func from another project in Code::Blocks

本文关键字:引用 函数 未定义 项目 另一个 代码      更新时间:2023-10-16

我在CodeBlocks中有两个项目:

图灵机

MyExp.h

class MyExp
{
public:
    MyExp() = default;
    double myExpFunc(double);
};

MyExp.cpp

#include "MyExp.h"
double MyExp::myExpFunc(double x) //fixed the lack of MyExp::, but still doesn't work
{ 
    return x*x;
}

第二个项目:TuringMachineTests

main.cpp

#include "../include/MyExp.h"
#define BOOST_TEST_MODULE MyTest
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_CASE( my_test )
{
        MyExp me;
        int val = me.myExpFunc(5.0);
        BOOST_CHECK_EQUAL(val, 24);
}

Boost的东西工作正常(不调用myExpFunc,一切正常)。路径也是正确的(图灵机测试的目录在图灵机的目录中)。

但编译器说:

||=== Build: Debug in TuringMachine (compiler: GNU GCC Compiler) ===|
||=== Build: Debug in TuringMachineTests (compiler: GNU GCC Compiler) ===|
obj/Debug/main.o||In function `my_test::test_method()':|
.../TuringMachine/TuringMachineTests/main.cpp|8|undefined reference to `MyExp::myExpFunc(double)'|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

听起来Tests项目找不到MyExp.cpp(请注意,默认的ctor是正常调用的)。有什么想法吗?

在实现方法时忘记了类名:

double MyExp::myExpFunc(double x)
//     ^^^^^^^
{
    ...
}

此外,您必须将文件"MyExp.cpp"添加到项目中。必须编译并链接该文件。否则,链接过程中将出现错误(未定义对"MyExp::myExpFunc"的引用)。