Linking C code with Cuda code

2019-07-26 16:30发布

问题:

So I'm writing a very basic CUDA code (vector addition) to teach myself the basics of CUDA programming. I've got it working when I write one .cu file, but now I am trying to make it work with a .c and .cu file linked together. My main.c file is as follows:

#include "Test.h"
#include <stdlib.h>

int main(int argc, char *argv[]) {
        int n = 1000;
        size_t size = n * sizeof(float);
        int i;

        float *h_a = malloc(size), *h_b = malloc(size), *h_c = malloc(size);

        for(i = 0; i < n; i++) {
                h_a[i] = h_b[i] = i;
        }

        addVec(h_a, h_b, h_c, n);

        exit(0);
}

Here, Test.h simply says:

void addVec(float *, float *, float *, int);

My vecAdd.cu file says:

#include "Test.h"

__global__ void vecAdd(float *a, float *b, float *c, int n) {
        int i = blockDim.x * blockIdx.x + threadIdx.x;

        if(i < n)
                c[i] = a[i] + b[i];
}

void addVec(float *a, float *b, float *c, int n) {
        float *d_a, *d_b, *d_c;
        size_t size = n * sizeof(float);

        cudaMalloc(&d_a, size);
        cudaMalloc(&d_b, size);
        cudaMalloc(&d_c, size);

        ...
}

I then run the commands:

gcc -c -Wall -O3 main.c -o ../obj/main.o
nvcc -c -O3 vecAdd.cu -o ../obj/vecAdd.o
gcc -L/usr/local/cuda/lib64 -lcudart ../obj/main.o ../obj/vecAdd.o -o ../bin/nvTest

The first two work fine. The last one, when I try to link the two object files, tells me that I have an undefined reference to addVec, though it is defined in vecAdd.cu... what am I doing wrong?

回答1:

You have a C/C++ linkage problem that is basically identical to that described here. This is because nvcc is using a c++ compiler for host code (creating c++ style linkage references i.e. "mangling") and gcc is interpreting main.c as a c (not c++) file and therefore creating c style linkage references.

There are at least 2 ways to fix it:

  1. convert your main.c into a main.cpp and use g++ where you are using gcc now (for your first and 3rd compile and link steps). Then everything will be consistently c++ style references.
  2. Declare within your C++ module (vecAdd.cu) that the external reference should be C style as described here.


标签: c linker cuda