undefined cudaMalloc符号

时间:2015-02-26 20:08:42

标签: macos cuda

我正在尝试从CUDA documentation

编译cublas示例
//Example 2. Application Using C and CUBLAS: 0-based indexing
//-----------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cuda_runtime.h>
#include "cublas_v2.h"
#define M 6
#define N 5
#define IDX2C(i,j,ld) (((j)*(ld))+(i))

static __inline__ void modify (cublasHandle_t handle, float *m, int ldm, int n, int p, int q, float alpha, float beta){
    cublasSscal (handle, n-p, &alpha, &m[IDX2C(p,q,ldm)], ldm);
    cublasSscal (handle, ldm-p, &beta, &m[IDX2C(p,q,ldm)], 1);
}

int main (void){
    cudaError_t cudaStat;    
    cublasStatus_t stat;
    cublasHandle_t handle;
    int i, j;
    float* devPtrA;
    float* a = 0;
    a = (float *)malloc (M * N * sizeof (*a));
    if (!a) {
        printf ("host memory allocation failed");
        return EXIT_FAILURE;
    }
    for (j = 0; j < N; j++) {
        for (i = 0; i < M; i++) {
            a[IDX2C(i,j,M)] = (float)(i * M + j + 1);
        }
    }
    cudaStat = cudaMalloc ((void**)&devPtrA, M*N*sizeof(*a));
    if (cudaStat != cudaSuccess) {
        printf ("device memory allocation failed");
        return EXIT_FAILURE;
    }
    stat = cublasCreate(&handle);
    if (stat != CUBLAS_STATUS_SUCCESS) {
        printf ("CUBLAS initialization failed\n");
        return EXIT_FAILURE;
    }
    stat = cublasSetMatrix (M, N, sizeof(*a), a, M, devPtrA, M);
    if (stat != CUBLAS_STATUS_SUCCESS) {
        printf ("data download failed");
        cudaFree (devPtrA);
        cublasDestroy(handle);
        return EXIT_FAILURE;
    }
    modify (handle, devPtrA, M, N, 1, 2, 16.0f, 12.0f);
    stat = cublasGetMatrix (M, N, sizeof(*a), devPtrA, M, a, M);
    if (stat != CUBLAS_STATUS_SUCCESS) {
        printf ("data upload failed");
        cudaFree (devPtrA);
        cublasDestroy(handle);
        return EXIT_FAILURE;
    }
    cudaFree (devPtrA);
    cublasDestroy(handle);
    for (j = 0; j < N; j++) {
        for (i = 0; i < M; i++) {
            printf ("%7.0f", a[IDX2C(i,j,M)]);
        }
        printf ("\n");
    }
    free(a);
    return EXIT_SUCCESS;
}

我将此文件保存到“cudaexample.c”中,并尝试使用gcc cudaexample.c -I/usr/local/cuda/include -L/usr/local/cuda/lib -lcuda -lcublas进行编译

我收到一个未定义的符号错误:

Undefined symbols for architecture x86_64:
  "_cudaFree", referenced from:
      _main in ccpPWjbO.o
  "_cudaMalloc", referenced from:
      _main in ccpPWjbO.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status

似乎我已经正确地指定了命令,因为找到了其他符号(例如cublasCreate)。为什么Free和Malloc不存在?

相关细节: OSX:10.10.2 gcc:4.8.4(目标:x86_64-apple-darwin14) 图形:NVIDA GeForce GT 650M 1024 MB

我下载并安装了CUDA-6.5工具包

1 个答案:

答案 0 :(得分:1)

这些API函数(例如cudaMalloc)包含在CUDA运行时库中。您没有链接到该库,因此在链接阶段找不到这些符号。

-lcudart添加到您的链接标记:

-I/usr/local/cuda/include -L/usr/local/cuda/lib -lcuda -lcublas -lcudart

它应该为你解决这个问题。

(仅当您使用CUDA 驱动程序 API函数时才需要-lcuda。如果您愿意,可以删除它。)