我在使用 C++ 程序时遇到问题。我想在 C++ 文件中使用在 C 文件中定义的函数。这是我的 C++ 文件代码:
#include <string>
#include <iostream>
#include <stdio.h>
extern void squre_array();
using namespace std;
int main() {
squre_array();
}
下面是我在其中定义 squre_array()
的 C 文件的代码:
#include <stdio.h>
#include <cuda.h>
__global__ void square_array(float *a, int N)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx<N)
a[idx] = a[idx] * a[idx];
}
void squre_array()
{
float *a_h, *a_d;
const int N = 10;
size_t size = N * sizeof(float);
a_h = (float *)malloc(size);
cudaMalloc((void **) &a_d, size);
for (int i=0; i<N; i++) a_h[i] = (float)i;
cudaMemcpy(a_d, a_h, size, cudaMemcpyHostToDevice);
int block_size = 4;
int n_blocks = N/block_size + (N%block_size == 0 ? 0:1);
square_array <<< n_blocks, block_size >>> (a_d, N);
cudaMemcpy(a_h, a_d, sizeof(float)*N, cudaMemcpyDeviceToHost);
// Print results
for (int i=0; i<N; i++) printf("%d %f\n", i, a_h[i]);
free(a_h);
cudaFree(a_d);
}
现在有人能告诉我如何将此函数链接到我的 C++ 程序吗? 每次编译程序时,我都会收到错误信息:
cpp:: undefined reference to `squre_array()'
谁能告诉我我做错了什么?
如何将 squre_array()
函数链接到我的 C++ 程序中?
最佳答案
在 C++ 代码中,您需要将 C 函数声明为 extern "C"
extern "C" void squre_array();
关于c - 从 C++ 程序中使用 C 函数 - extern 关键字问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5321567/