在ubuntu中,使用c++ 编程语言,在.cpp文件中调用 .cu文件中的函数实现,文件列表如下:
project_dir:
----CmakeList.txt
----main.cpp
----test.cu
----test.h
在test.cu文件中实现cuda相关的代码,在test.h中声明test.cu中的函数,test.h文件中的内容示例如下:
#ifndef TEST_VTK_GPU_PROCESS_H
#define TEST_VTK_GPU_PROCESS_H
#include <mutex>
#include <atomic>
#include <vector>
#include <chrono>
#include <iostream>
#include <fstream>
#include <string.h>
typedef pcl::PointXYZI PointType;
typedef pcl::PointCloud<PointType> Cloud;
typedef Cloud::Ptr CloudPtr;
点云数据加载函数的声明
extern "C" void data_load(int start_frame,int end_frame,std::string &pcd_root_dir);
#endif //TEST_VTK_GPU_PROCESS_H
test.cu文件中的内容示例如下:
#include "test.h"
//点云数据加载
extern "C" void data_load(int start_frame,int end_frame,std::string &pcd_root_dir)
{
for (int i = start_frame; i < end_frame; ++i) {
std::string pcd_file_path = pcd_root_dir + std::to_string(i) + ".pcd";
CloudPtr original_cloud(new Cloud);
if (pcl::io::loadPCDFile<PointType>(pcd_file_path, *original_cloud) == -1) {
PCL_ERROR("Couldn't read file: %s.\n", pcd_file_path.c_str());
}
}
}
在main.cpp中想要实现对test.cu文件中函数的调用,内容示例如下:
#include <iostream>
#include "gpu_process.h"
int start_frame = 0;
int end_frame = 90000;
std::string pcd_root_dir = "/home/les/MyCode/pcd/";
int main()
{
std::cout << "Hello, World!" << std::endl;
data_load(start_frame, end_frame, pcd_root_dir);
return 0;
}
为了能够正常实现调用,还需要在CmakeList.txt文件中做如下配置:
cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
set(CMAKE_CXX_STANDARD 17)
project(test_cloud LANGUAGES CXX CUDA) # *** 一定要设置 LANGUAGES CXX CUDA,否则不能运行
set(CMAKE_BUILD_TYPE Debug)
#pcl 1.12
find_package(PCL 1.12 REQUIRED)
#include_directories(${PCL_INCLUDE_DIRS})
link_directories(${PCL_LIBRARY_DIRS})
add_definitions(${PCL_DEFINITIONS})
#eigen3
find_package(Eigen3 REQUIRED)
include_directories(${EIGEN3_INCLUDE_DIR})
include_directories("/usr/include/eigen3")
#cuda 设置cuda环境
find_package(CUDA REQUIRED)
set(CMAKE_CUDA_ARCHITECTURES 60 61 62 70 72 75 86 89 90)
set(CMAKE_CUDA_COMPILER /usr/local/cuda/bin/nvcc)
set(CUDA_TOOLKIT_ROOT_DIR "/usr/local/cuda")
# use_fast_math: 加速CUDA程序的执行,但可能会导致精度损失
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} --use_fast_math")
# 添加待编译的文件
add_executable(test_cloud test.cu test.h main.cpp)
# 连接对应库
target_link_libraries (test_cloud
${PCL_LIBRARIES}
-lpthread
sqlite3
zlog
rt
mysqlclient
${PCL_COMMON_LIBRARIES}
${PCL_IO_LIBRARIES}
${CUDA_LIBRARIES}
${OpenCV_LIBRARIES}
pthread)