Code::Blocks 中另一个项目对 func 的未定义引用

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

我在 CodeBlocks 中有 2 个项目:

图灵机

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 正常工作(w/o 调用 myExpFunc 一切正常)。路径也正确(TuringMachineTest 的目录在 TuringMachine 的目录中)。

但是编译器说:

||=== 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)) ===|

听起来测试项目找不到MyExp.cpp(注意默认ctor被正常调用)。有什么想法吗?

您忘记了 class 名称,在执行您的方法时:

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

此外,您必须将文件 'MyExp.cpp' 添加到项目中。该文件必须被编译和链接。否则您将在链接期间遇到错误(对 `MyExp::myExpFunc' 的未定义引用)。