【问题标题】:C++ : "undefined reference to" probably because of CMake filesC++:“未定义的引用”可能是因为 CMake 文件
【发布时间】:2018-07-27 16:03:50
【问题描述】:

感谢 mascoj 的帮助,我在 CMake 中遇到了一个问题。现在我有了这个我运行 SocketTests 文件的测试:“空测试套件”

如果我在课堂内点菜,则测试有效。这是项目的架构:

+-- CMakeLists.txt
+-- Serveur
|    +-- CMakeLists.txt
|    +-- Serveur.cpp
|    +-- Serveur.h
|    +-- Socket.cpp
|    +-- Socket.h
|
+-- Tests
|    +-- CMakeLists.txt
|    +-- main.cpp
|    +-- lib
|    +-- ServeurTests
|       +-- SocketTests.cpp

不同的文件: ./ CMakeLists.txt :

cmake_minimum_required(VERSION 3.10)
project(ServeurCheckIn)

set(CMAKE_CXX_STANDARD 14)
add_subdirectory(Serveur)
add_subdirectory(Tests)

Serveur/CMakeLists.txt:

cmake_minimum_required(VERSION 3.10)
project(ServeurCheckIn)

set(CMAKE_CXX_STANDARD 14)

add_library(ServeurCheckIn SHARED Serveur.cpp Serveur.h Socket.cpp Socket.h)

服务器/Socket.h:

#include <sys/socket.h>
#include <netinet/in.h>

namespace Serveur
{
    class Socket
    {
        public:
            Socket(int domaine, int type, int protocole);

            int Domaine();
            int Type();
            int Protocole();

        private:
            int _domaine;
            int _type;
            int _protocole;
    };
}

服务器/Socket.cpp:

#include "Socket.h"

using namespace Serveur;

Socket::Socket(int domaine, int type, int protocole) :
    _domaine(domaine), _type(type), _protocole(protocole)
{
}

int Socket::Domaine()
{
    return _domaine;
}

int Socket::Type()
{
    return _type;
}

int Socket::Protocole()
{
    return _protocole;
}

测试/CMakeLists.txt:

cmake_minimum_required(VERSION 3.10)
project(Tests)

set(CMAKE_CXX_STANDARD 14)

add_subdirectory(lib/googletest-master)
include_directories(lib/googletest-master/googletest/include)
include_directories(lib/googletest-master/googlemock/include)

add_executable(Tests main.cpp ServeurTests/SocketTests.cpp )
target_link_libraries(Tests gtest gtest_main ServeurCheckIn)
enable_testing()

测试/SocketTests.cpp:

#include <gtest/gtest.h>
#include "../../Serveur/Serveur.h"

using namespace Serveur;

class SocketTests : public testing::Test
{
    public:
        SocketTests() : _socket(AF_INET, SOCK_RAW, IPPROTO_IP)
        {
        }
    protected:
        Socket _socket;
};

TEST_F(SocketTests, CreateSocket_SocketIsCreated)
{
    ASSERT_EQ(1, 1);
}

【问题讨论】:

  • 这可能与问题无关,但您在Serveur 中有错字。
  • Tsyvarev 我认为问题出在 mascoj 强调的 CMake 中。
  • Ptaq666 好点,但它是法语
  • 是的,问题出在CMakeLists.txt。因为您没有与库链接,所以出现“未定义的引用”错误。正是在引用的问题中描述的。你会问“如何在 CMake 中链接库”,你会发现另一个问题,它描述了这一点。至于当前的问题,在 CMake 中使用 add_test 命令创建测试。我在您的代码中没有看到对此命令的调用。

标签: c++ cmake googletest


【解决方案1】:

您的 Tests 可执行文件需要与您使用其他 CMake 创建的库链接。

target_link_libraries(Tests gtest gtest_main ServeurCheckIn)

没有它,这些函数的定义将不会在链接时出现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    相关资源
    最近更新 更多