C ++构造函数未定义

Jus*_*Dev 1 c++ cmake

我从事C ++项目,我使用CMake构建文件。我的构建失败原因

未定义对`Software :: Software()的引用

,但我看不到问题。如果您有想法,请不要犹豫,谢谢

文件架构:

在此处输入图片说明

CMake的:

# cmake_minimum_required(VERSION <specify CMake version here>)
project(untitled)

cmake_minimum_required(VERSION 2.8.9)
set(CMAKE_CXX_STANDARD 11)

include_directories(include)

file(GLOB SOURCES "src/*.cpp")
add_executable(untitled ${SOURCES})
Run Code Online (Sandbox Code Playgroud)

Software.h:

#include <string>
class Software{
    private : 
        std::string name;

    public :
        Software();
}
Run Code Online (Sandbox Code Playgroud)

Software.cpp:

#include "Software.h"

Software::Software() {
    this->name = "defaultName";
}
Run Code Online (Sandbox Code Playgroud)

SoftwaresConfigurations.h(称为软件的构造者):

#include "Software.h"

class SoftwaresConfigurations {
    public:
        SoftwaresConfigurations();
}
Run Code Online (Sandbox Code Playgroud)

SoftwaresConfiguration.cpp:

#include "SoftwaresConfigurations.h"

SoftwaresConfigurations::SoftwaresConfigurations(){
    Software software = Software();
}
Run Code Online (Sandbox Code Playgroud)

Bot*_*tje 5

You have fallen into the trap that is FILE(GLOB ...). Re-running CMake should fix this, but you should probably move away from using GLOB to collect your source files. For example, you can list them explicitly as follows:

set(SOURCES src/main.cpp src/Softwares.cpp src/SoftwaresConfigurations.cpp)
Run Code Online (Sandbox Code Playgroud)

I will explain what happened below.

The official documentation says the following:

我们不建议使用GLOB从源代码树中收集源文件列表。如果在添加或删除源时没有CMakeLists.txt文件更改,则生成的生成系统无法知道何时要求CMake重新生成。

因此,可能发生的情况是您仅使用一个源文件创建了项目。CMake GLOB在配置时运行了,并仅找到一个.cpp文件。然后,您添加了两个文件(CMake不知道),并将添加#include到您的文件中SoftwaresConfiguration.cpp。这会触发重建。但是,由于CMake不知道Softwares.cpp,所以它不会生成该文件,并且链接程序会生成未引用的符号。

  • @Botje我会改为`target_sources(target PRIVATE ...)`,但要注意! (2认同)