c++ - 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 to
charout(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 时却不行?
解决方案
推荐阅读
- javascript - 使用空项目安装 vue-cli 时出现问题
- javascript - 如何使用“包含”参数在可放置 Div 中包含拖动的克隆元素
- r - 如何在 kable pdf 输出中跨行拆分整个单词以防止文本与下一个单元格重叠
- java - 'Access-Control-Allow-Origin' 标头包含多个值 ', *',但在 spring boot stomp 配置中只允许一个值
- android - 如何更改 WPA 中 P2P-DEVICE-FOUND 事件的 DeviceCapability?
- jsonpath - 如何匹配 JsonPath 中的值
- sonos - 在不暂停音乐的情况下将播放器添加到现有组?
- jenkins - 如果我在 AWS EKS 上配置了 Jenkins 主服务器,如何通过 JNLP 设置 Windows 从属代理
- amazon-web-services - 模型批准后终端节点未在 AWS Sagemaker 中创建
- python-3.x - 尝试在Firefox中打开多个配置文件并通过子进程python以隐身模式搜索