2

我正在尝试转换我拥有的使用随机库的 c++ 程序,该库是 C++11 功能。在这里阅读了几篇类似的帖子后,我尝试将代码分成三个文件。首先,我想说我对 C/C++ 不是很熟悉,并且主要在工作中使用 R。

主文件如下所示。

#ifndef _KERNEL_SUPPORT_
#define _KERNEL_SUPPORT_
#include <complex>
#include <random>
#include <iostream>
#include "my_code_header.h"
using namespace std;
std::default_random_engine generator;
std::normal_distribution<double> distribution(0.0,1.0);
const int rand_mat_length = 24561;
double rand_mat[rand_mat_length];// = {0};
void create_std_norm(){
  for(int i = 0 ; i < rand_mat_length ; i++)
    ::rand_mat[i] = distribution(generator);
}
.
.
.
int main(void)
{
  ...
  ...
  call_global();
  return 0;
}
#endif

头文件如下所示。

#ifndef mykernel_h
#define mykernel_h
void call_global();
void two_d_example(double *a, double *b, double *my_result, size_t length, size_t width);
#endif

.cu 文件如下所示。

#ifndef _MY_KERNEL_
#define _MY_KERNEL_
#include <iostream>
#include "my_code_header.h"
#define TILE_WIDTH 8
using namespace std;
__global__ void two_d_example(double *a, double *b, double *my_result, size_t length, size_t width)
{
  unsigned int row = blockIdx.y*blockDim.y + threadIdx.y;
  unsigned int col = blockIdx.x*blockDim.x + threadIdx.x;
  if ((row>length) || (col>width)) {
    return;
  }
  ... 
}
void call_global()
{
  const size_t imageLength = 528;
  const size_t imageWidth = 528;
  const dim3 threadsPerBlock(TILE_WIDTH,TILE_WIDTH);
  const dim3 numBlocks(((imageLength) / threadsPerBlock.x), ((imageWidth) / threadsPerBlock.y));
  double *d_a, *d_b, *mys ;

  ...
  cudaMalloc((void**)&d_a, sizeof(double) * imageLength);
  cudaMalloc((void**)&d_b, sizeof(double) * imageWidth);
  cudaMalloc((void**)&mys, sizeof(double) * imageLength * imageWidth);

  two_d_example<<<numBlocks,threadsPerBlock>>>(d_a, d_b, mys, imageLength, imageWidth);
  ...  
  cudaFree(d_a);
  cudaFree(d_b);


}

#endif

请注意,__global__已经从 .h 中删除了,因为我收到以下错误,因为它是由 g++ 编译的。

In file included from my_code_main.cpp:12:0:
my_code_header.h:5:1: error: ‘__global__’ does not name a type

当我用 nvcc 编译 .cu 文件时,一切都很好,并生成了一个 my_code_kernel.o。但由于我在我的 .cpp 中使用 C++11,所以我试图用 g++ 编译它,我收到以下错误。

/tmp/ccR2rXzf.o: In function `main':
my_code_main.cpp:(.text+0x1c4): undefined reference to `call_global()'
collect2: ld returned 1 exit status

我知道这可能不需要对 CUDA 做任何事情,并且可能只是在两个地方都包含标题的错误使用。还有什么是正确的编译方法,最重要的是链接 my_code_kernel.o 和 my_code_main.o(希望如此)?对不起,如果这个问题太琐碎了!

4

1 回答 1

2

看起来您没有与 my_code_kernel.o 链接。你已经使用-c了你的 nvcc 命令(导致它编译但不链接,即生成 .o 文件),我猜你没有使用-c你的 g++ 命令,在这种情况下你需要添加 my_code_kernel。 o 到输入列表以及 .cpp 文件。

您试图实现的分离是完全可能的,只是看起来您没有正确链接。如果您仍有问题,请将编译命令添加到您的问题中。

仅供参考:您不需要two_d_example()在头文件中声明,它仅在您的 .cu 文件中使用(来自call_global())。

于 2013-08-16T08:12:31.683 回答