c - 从 C++ 程序中使用 C 函数 - extern 关键字问题

标签 c extern

我在使用 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/

相关文章:

无法将变量分配给 C 中的外部变量

c - 我如何才能比其他人更快地获得此 C 代码?

c - xcode上C程序的逻辑错误

c - 段错误 11 从结构打印字符串

c - 如何根据表的大小导出常量

c - C 中的外部声明和头文件

c - float 的最大值

objective-c - 等同于 public static final 变量

c - 在 2 个文件 (linux/windows) 版本之间使用 extern 变量

局部变量和寄存器变量可以声明为外部吗?