如果坚持在头文件中定义全局对象,确保只在一个源文件中包含 xxx.h 头文件的定义,否则会导致重复定义错误。通常推荐的做法是将全局对象的定义放在一个 .cpp 文件中,并在头文件中只声明它(使用 extern),这样可以更好地管理全局对象的生命周期并避免链接错误。
推荐做法:把全局对象的定义移到一个 .cpp 文件中,头文件中只声明它。例如:
// xxx.h
#ifndef XXX_H
#define XXX_H
#include <vector>
#include <memory>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
extern std::vector<std::shared_ptr<pcl::PointCloud<pcl::PointXYZ>>> pointClouds; // 仅声明
void someFunction();
#endif // XXX_H
// xxx.cpp
#include "xxx.h"
// 在此定义全局对象
std::vector<std::shared_ptr<pcl::PointCloud<pcl::PointXYZ>>> pointClouds;
void someFunction() {
// 使用 pointClouds
}
这样,就能够避免多重定义的问题,同时保持代码的清晰和可维护性。