[SOLVED] Error with 'constant memory'

Hi,

I’m trying to save some variables in constant memory but I get some errors when nvcc links the program.

I have a C++ class that invokes some kernels. My *h and *cpp files are like:

myClass.h:

#include "kernels.h"
class myClass
{
    private:
        //some fields and private functions

    public:
        void invokeKernel(...);

}

myClass.cpp:

#include "myClass.h"

void myClass:myClass invokeKernel(...)
{
    ...
    for (i = 0; i < N; i++) {
        launchKernel<<<gridSize, blockSize>>>(v);
    }
    ...
}

The kernel is inside *h file:

kernels.h:

__global__ void launchKernel(double value)
{
    //do something
}

I want to save the variable “value” in constant memory, I have tried to add the constant qualifier in the file ‘kernels.h’ and copy the value before launch the kernel:

kernels.h:
__constant__ double value;
__global__ void launchKernel()
{
    //do something
}

myClass.cpp:

#include "myClass.h"

void myClass:myClass invokeKernel(...)
{
    ...
    for (i = 0; i < N; i++) {
        cudaMemcpyToSymbol(&value, &v, sizeof(double), 0, cudaMemcpyHostToDevice);
        launchKernel<<<gridSize, blockSize>>>();
    }
    ...
}

When I try to compile and linkk the program I get the follow error:

...
nvlink error   : Multiple definition of 'value' in 'build/Release_64b_CUDA/GNU+CUDA-Linux/otherClass1.o', first defined in 'build/Release_64b_CUDA/GNU+CUDA-Linux/otherClass2.o'
...

I don’t understand correctly the message because the variable ‘value’ only is defined in file ‘kernel.h’. Do I need define it in other file?

Thank you.

Just like in C/C++, no variables should be defined in header files, because that just leads to multiple instances if the header is included into multiple files.

Instead, you just declare the variable in the header file, and then create a single instance by just defining the variable once in a .c/.cpp/.cu file:

// consts.h
extern __constant__ double value;
// consts.cu
#include "consts.h"
__constant__ double value;

[url=“http://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#examples”]http://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#examples[/url]

Thank you tera!

You are right, this was the problem, I had not thought of this.