【问题标题】:undefined reference to `func()' (multi-file compilation) [duplicate]未定义对“func()”的引用(多文件编译)[重复]
【发布时间】:2020-11-12 14:29:06
【问题描述】:

我对 C++ 上的多文件编译非常陌生,我试图通过测试来理解它。 但在下面的示例中,我收到了一个错误undefined reference to `func()',我不明白为什么。 提前致谢!

Main.cpp

#include <iostream>
#include "file1.h"

int main() {
    func();
    return 0;
}

文件1.h

#ifndef UNTITLED1_FILE1_H
#define UNTITLED1_FILE1_H
#include <iostream>

void func();

#endif //UNTITLED1_FILE1_H

文件 1.cpp

#include "file1.h"

void func() {
    std::cout << "Test" << std::endl;
}

CMAKELIST

cmake_minimum_required(VERSION 3.17)
project(untitled1)

set(CMAKE_CXX_STANDARD 14)

add_executable(untitled1 main.cpp file1.h)

【问题讨论】:

  • 你是如何构建它的?您使用一些构建管理器还是手动执行?请提供您正在使用的命令。
  • 提供你的编译行。
  • 您需要在 cmake 中将 file1.cpp 添加到您的可执行文件中

标签: c++ cmake


【解决方案1】:

基本上,您还没有包含所有源文件。你也没有指定你的包含目录。

cmake_minimum_required(VERSION 3.17)

# Never name your project the same thing as any of your targets
project(COOL_PROJECT)

set(CMAKE_CXX_STANDARD 14)

add_executable(untitled1)

# You must include all source files, header files are optional.
# However adding header files explicitly will result in better IDE support
#
# Prefer to add source files using target_sources instead
target_sources(untitled1 PRIVATE
    main.cpp
    file1.cpp
    file1.h
)

# Add your current directory as an include directory.
target_include_directories(untitiled PRIVATE ${CMAKE_CURRENT_LIST_DIR})

顺便说一句,外壳很重要。所以请确保文件名大小写匹配。

文件 1.cpp != 文件 1.cpp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-16
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 2018-03-28
    • 2012-08-16
    相关资源
    最近更新 更多