问题
I need to write the code into several .cu files. But where should I define the device variables which are use for many .cu files.
An example
File common.h
__device__ int x;
File A.cu
__global__ void a()
File B.cu
__global__ void b()
a(),b() both use x. what should I do?
In C language, I should write something like extern device int x; Then I define device int x in another place. But in CUDA I can not do it. If I do, it tells me ‘..........’ previously declared here
回答1:
EDIT : @talonmies was right (as usual). So I've deleted my comment about CUDA 4.1
Furthermore the compiling commands I gave were not quite right. So let me replace my answer with one that demonstrably works and has the proper instructions.
You need CUDA 5.0 and a compute capability 2.0 or greater device for this to work.
I'm sure there's probably a better way, but this seems to work for me:
com.h:
#ifndef DEVMAIN
extern __device__ int x;
#endif
a.cu:
#include "com.h"
__global__ void a(){
x = -5;
}
b.cu:
#include <stdio.h>
#define DEVMAIN
#include "com.h"
extern __global__ void a();
__device__ int x;
__global__ void b(){
x = 5;
}
int main() {
int temp=7;
cudaMemcpyToSymbol(x,&temp, sizeof(int));
a<<<1,1>>>();
cudaMemcpyFromSymbol(&temp,x,sizeof(int));
printf("in host : %d\n",temp);
b<<<1,1>>>();
cudaMemcpyFromSymbol(&temp,x,sizeof(int));
printf("in host2 : %d\n",temp);
return 0;
}
compiling:
nvcc -arch=sm_20 -dc a.cu
nvcc -arch=sm_20 -dc b.cu
nvcc -arch=sm_20 -o ab a.o b.o
output:
$ ./ab
in host : -5
in host2 : 5
$
Sorry for my previous errors.
来源:https://stackoverflow.com/questions/13597707/how-to-use-extern-cuda-device-variables