首页 > 解决方案 > C++ CMake没有正确引用.h的函数

问题描述

解决方案:不要成为菜鸟并在与 您的回答make相同的目录中运行!cmake

我从 C++ 编程开始,我试图了解如何使用 .h 和 .cpp 文件正确引用函数。我有以下文件:

    \\func.h
    #ifndef FUNC_H
    #define FUNC_H

    int charout(int a, char b);

    #endif

    \\func.cpp
    #include <iostream>
    #include "func.h"
    using namespace std;

    int charout(int a, char b)
    {
        cout << a;
        cout << b;
    return 0;
    }

\\main.cpp
#include <iostream>
#include "func.h"
using namespace std;

int main ()
{
    int a; char b;

    cout << "insert an integer " << endl;
    cin >> a;
    cout << "insert a letter " << endl;
    cin >> b;
    charout(a,b);
return 0;
}

我正在使用具有以下结构的 CMake(在文件夹“include”中使用 func.h)进行编译:

# Declare the version of the CMake API for forward-compatibility
cmake_minimum_required(VERSION 2.8)
# Declare the name of the CMake Project
project(manual)
# Add the directory to search for header files
include_directories(include)
# Define an executable target
add_executable(main func.cpp main.cpp)

当我尝试制作 main.cpp 时,我收到一个错误:

make main g++ main.cpp -o main /tmp/cctlsXUG.o: In function main': main.cpp:(.text+0x80): undefined reference tocharout(int, char)' collect2: error: ld returned 1 exit status : recipe for target 'main' failed make: *** [main]错误 1

你能看看,让我知道我在哪里做错了吗?我会很感激你的反馈。我真的坚持这一点。干杯!


更新: 好的, g++ func.cpp main.cpp - o main 当我尝试用 gcc 编译相同的代码时,我设法编译了它,我遇到了一些错误,undefined reference to std::cout' 我发现 gcc 不能访问 C++ 的 std。我可以以某种方式修复我的 CMake 文件以使用 g++ 而不是 gcc 吗?我必须交付的项目应该包含一个 CMakeLists.txt。最后一个问题:为什么 CMake 在同一个文件中可以很好地处理函数声明和 main,但是当我将函数拆分为 header、cpp 和 main 时却不行?

标签: c++compiler-errorscmakereferenceheader

解决方案


推荐阅读