首页 > 解决方案 > 对使用 CMake 生成为 lib .a 的方法的未定义引用

问题描述

你能解释一下为什么我的函数AllToAll在我的例子中是未定义的吗?我使用 CMake 生成示例调用的 libNeuralNetwork.a。

层工厂.hpp

#pragma once
#include "LayerModel.hpp"
#include "Layer.hpp"

namespace nn
{
    extern internal::LayerModel AllToAll(int numberOfNeurons, activationFunction activation = sigmoid);
}

层工厂.cpp

#include "LayerFactory.hpp"
#include "AllToAll.hpp"

using namespace nn;
using namespace internal;

LayerModel AllToAll(int numberOfNeurons, activationFunction activation)
{
    LayerModel model
    {
        allToAll,
        activation,
        numberOfNeurons
    };
    return model;
}

神经网络.hpp

#pragma once
#include "layer/LayerModel.hpp"
#include "layer/LayerFactory.hpp"

namespace nn
{
    class NeuralNetwork
    {
    public:
        NeuralNetwork(int numberOfInputs, std::vector<internal::LayerModel> models);
        //...
    };
}

例子.cpp

#include "../src/neural_network/NeuralNetwork.hpp"

using namespace nn;

int example1()
{
    NeuralNetwork neuralNetwork(3, {AllToAll(5), AllToAll(2)});
}

错误信息:

CMakeFiles/UnitTests.out.dir/ExamplesTest.cpp.o: In function `example1()':
ExamplesTest.cpp:(.text+0x8b3): undefined reference to `nn::AllToAll(int, nn::activationFunction)'

标签: c++cmake

解决方案


您已AllToAll在顶级命名空间中声明并在命名空间中定义它nn

以下不会在命名空间中声明函数:

using namespace foo;

extern void Bar();

你需要:

namespace foo {
  extern void Bar();
}

推荐阅读