问题:使用vscode初学c++,学习函数的分文件编写。遇到报错:
ld: symbol(s) not found for architecture x86_64clang: error: linker command failed with exit code 1
函数分文件编写一般有四个步骤:
创建后缀名为.h的头文件
创建后缀名为.cpp的源文件
在头文件中写函数声明
在源文件中写函数定义
函数声明的头文件 swap.h
#includeusing namespace std; //函数的声明 void swap(int a, int b);
函数定义的源文件 swap.cpp
#include "swap.h"
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
包含main函数的源文件
// #include// using namespace std; #include "swap.h" int main() { int a = 10; int b = 20; swap(a, b); system("pause"); return 0; }
报错:
Undefined symbols for architecture x86_64:
"swap(int, int)", referenced from:
_main in function_fenfile-bed1a8.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
解决:
在包含main函数的源文件中,加入
#include "swap.cpp"
运行成功
最终的包含main函数的源文件:
// #include// using namespace std; #include "swap.h" #include "swap.cpp" int main() { int a = 10; int b = 20; swap(a, b); system("pause"); return 0; }
注意:主程序中不仅要包含头文件,还要包含函数文件。
参考:
CLion报错:Undefined symbols for architecture x86_64:的问题与解决方案_Pwn方程式-CSDN博客



