c++ - 如何在 C++ 中包含头文件和实现文件?
问题描述
我正在学习 c++,讲师制作了一个关于如何在多个文件中制作类和函数的视频。
我有 3 个简单的 c++ 文件,分别称为“main.cpp”、“something.h”和“something.cpp”,它们都在同一个目录中,没有其他文件。(他们在下面)
问题是链接器正在抛出错误消息,我真的不知道为什么。(也许我只是错过了一些非常明显的东西)
// main.cpp
#include <iostream>
#include "something.h"
int main(){
int a{2}, b{2};
std::cout << add(a,b) << std::endl;
int arr[5] {1,2,4,8,16};
print_arr(arr, 5);
std::cout << "Hello, world\n";
return 0;
}
// something.h
#ifndef _SOMETHING_H_
#define _SOMETHING_H_
int add(int a, int b);
void print_arr(int* arr, unsigned int size);
#endif // _SOMETHING_H_
// something.cpp
#include "something.h"
#include <iostream>
int add(int a, int b){
return a+b;
}
void print_arr(int* arr, unsigned int size){
std::cout << "{ ";
for (int i = 0; i < size; i++)
std::cout << arr << ' ';
std::cout << '}';
}
错误:
Undefined symbols for architecture x86_64:
"add(int, int)", referenced from:
_main in main-06aa98.o
"print_arr(int*, unsigned int)", referenced from:
_main in main-06aa98.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
解决方案
最简单的,clang++ -Wall -g something.cpp main.cpp -o main
.
您也可以something.cpp
先编译以创建something.o
...
clang++ -Wall -g -c something.cpp
...然后在编译时指定链接main.cpp
:
clang++ -Wall -g main.cpp something.o
最后一种方法可以更好地扩展,就好像您只更改main.cpp
您可以只执行第二步而无需重新编译something.o
.
推荐阅读
- javascript - 如何过滤html中的项目?
- typo3 - 占位符在哪里使用?
- regex - 如何提取SAS程序中所有使用的函数?
- php - 无法更改 Content-Type 标头 Soap PHP
- html - 媒体断点没有正确应用,可能很简单
- json - 如何简化一个jq句子?
- xml - 在 Python 中将具有属性的元素添加到 XML
- c# - Task.WhenAll.Partitioner.Create().GetPartitions(2).Select() 显示三个ThreadId
- python - 我想将歌曲的名称作为参数传递
- microsoft-teams - 在另一个团队中复制应用程序和选项卡的设置配置