c++是一种高级编程语言,具有强大的功能和灵活的特性,但在使用c++编写程序时可能会遇到许多错误。其中,无法解析的外部符号是一种常见的错误,指的是编译器无法找到编译程序所需要的函数或变量的定义的情况。本文将从几个方面阐述c++无法解析的外部符号。
一、c++无法解析的外部函数
// main.cpp
#include "other.h"
int main() {
hello_world();
return 0;
}
// other.h
void hello_world();
如上代码所示,main函数需要调用hello_world函数,但在main.cpp中并没有定义该函数的具体实现,而是在other.h头文件中声明了该函数。因此,在编译main.cpp时,会出现“无法解析的外部符号”错误。解决该问题的方法是在main.cpp中引用other.cpp文件,该文件中定义了hello_world函数的实现代码。
二、头文件遗漏导致的c++无法解析的外部符号
// main.cpp
#include "other.h"
int main() {
hello_world();
return 0;
}
// other.h
void hello_world();
// other.cpp
#include
void hello_world() {
std::cout << "Hello World!" << std::endl;
}
如上代码所示,虽然在编写main.cpp时已经引入了other.h头文件,但是其实现代码在other.cpp中,如果忘记引入other.cpp文件,仍会出现"c++无法解析的外部符号"错误。解决方法是在makefile中加入相应的.cpp文件。
三、命名空间不匹配导致的c++无法解析的外部符号
// main.cpp
#include "other.h"
int main() {
MyNamespace::hello_world();
return 0;
}
// other.h
namespace MyNamespace {
void hello_world();
}
// other.cpp
#include
namespace MyNamespace {
void hello_world() {
std::cout << "Hello World!" << std::endl;
}
}
虽然在other.h中声明了hello_world函数实现在MyNamespace命名空间中,但是如果在main函数中没有加上MyNamespace前缀,也会导致“无法解析的外部符号”的错误。
四、代码行顺序不正确导致的c++无法解析的外部符号
// main.cpp
#include "other.h"
int main() {
hello_world();
return 0;
}
// other.cpp
void hello_world() {
std::cout << "Hello World!" << std::endl;
}
// other.h
void hello_world();
如上代码所示,other.h头文件中声明了hello_world函数,而在other.cpp中定义了该函数的实现。但是,虽然main.cpp中引用了other.h头文件,但该文件却位于other.cpp后面,导致编译器在编译main.cpp时找不到hello_world函数的定义。
五、缺少库文件导致的c++无法解析的外部符号
// main.cpp
#include
#include
Int main()
{
cv::Mat image = cv::imread("image.jpg");
cv::imshow("Image",image);
cv::waitKey(0);
return 0;
}
如上代码所示,程序在使用OpenCV库的函数时,可能会出现"c++无法解析的外部符号"错误。其中一个常见的原因就是在编译过程中缺少了必要的库文件。编译器需要在编译期输出一个Windows PE文件,但必须链接器把可执行程序与库文件合并成一个完整的文件,否则编译器发现需要的库文件不存在,就会提示编译错误。