如何解决多个.cu,.h和.c文件之间的Nsight CUDA链接问题
这是我第一次尝试在NSight Ubuntu中构建CUDA应用程序以从优化和性能分析中受益。在Ubuntu 20(或18,16)中,使用nvcc
(makefile)在终端上运行此应用可以正常工作。我有多个.cu,.c和.h文件。首先将所有文件包含在flags.h文件中。我的代码以main.cu(具有main()
功能)文件开头,并且此文件具有#include“ flags.h”,以确保包含所有文件来编译代码。
flags.h还有很多#define
,以后还会在不同的.cu和.c文件中使用。
但是,在NSight中,flags.h中定义的#define参数在任何文件中都无法识别,并且出现错误。 以下是错误的屏幕截图。 我附加了一个简单的square_array问题,分为3个文件(main.cu,flags.h和square_.cu)。
我无法在NSight中构建它。有人可以尝试构建它,并让我知道。 任何帮助或建议将不胜感激。
main.cu
#include <stdio.h>
#include <stdlib.h>
#include "flags.h"
int main(void) {
int i;
int *a_h,*a_d;
CUDA_CHECK_RETURN(cudaMalloc((void**) &a_d,sizeof(int) * WORK_SIZE));
a_h = (int *)malloc(sizeof(int) * WORK_SIZE); // Allocate array on host
for (i = 0; i < WORK_SIZE; i++)
a_h[i] = i+2.;
int block_size = 4;
int n_blocks = WORK_SIZE/block_size + (WORK_SIZE%block_size == 0 ? 0:1);
sq_array<<<n_blocks,block_size>>>(a_d);
CUDA_CHECK_RETURN(cudaGetLastError());
CUDA_CHECK_RETURN(cudaMemcpy(a_h,a_d,sizeof(int) * WORK_SIZE,cudaMemcpyDeviceToHost));
for (i = 0; i < WORK_SIZE; i++)
printf("Input value: %d \n",a_h[i] );
CUDA_CHECK_RETURN(cudaFree((void*) a_d));
CUDA_CHECK_RETURN(cudaDeviceReset());
return 0;
}
flags.h
#ifndef FLAGS_H_
#define FLAGS_H_
#include "square_.cu"
#define CUDA_CHECK_RETURN(value) { \
cudaError_t _m_cudaStat = value; \
if (_m_cudaStat != cudaSuccess) { \
fprintf(stderr,"Error %s at line %d in file %s\n",\
cudaGetErrorString(_m_cudaStat),__LINE__,__FILE__); \
exit(1); \
} }
#define WORK_SIZE 29
#endif /* FLAGS_H_ */
square_.cu
__global__ void sq_array( int *a) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx< WORK_SIZE) a[idx] = a[idx] * a[idx];
}
解决方法
问题在于您的IDE正在编译square_.cu
并正在编译main.cu
,这也是 还要由于{{1} {1}}为您提供square_.cu
的两个定义。编译#include "square_.cu"
时,未定义flags.h
宏,从而导致编译时错误。在命令行上编译时,没有编译sq_array
,因此避免了此错误。
在任何情况下,square_.cu
WORK_SIZE
(或square_.cu
个文件)都是一个坏主意。这些文件应分别编译,然后链接在一起。
您必须以不同的方式组织事情。 我不知道您的代码的详细信息,但是您可以执行以下操作:
#include
:
.cu
.c
:
square.cu
您可以放心#include "square.h"
__global__ void sq_array( int *a) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx< WORK_SIZE) a[idx] = a[idx] * a[idx];
}
void host_sq_array(int *a_d) {
int block_size = 4;
int n_blocks = WORK_SIZE/block_size + (WORK_SIZE%block_size == 0 ? 0:1);
sq_array<<<n_blocks,block_size>>>(a_d);
}
,其中仅包括常量,类型定义和函数原型。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。