我有一个使用了一些库的主要代码,我一直在这样编译它:
gcc importedCFile1.c importedCFile2.c mainCode.c -O3 -lm -Wall -o maincode -lrt
现在我已经在 mainCode 中添加了 CUDA 代码,并将其扩展名更改为 .cu...那么,我该如何编译整个代码呢?
我试过:
nvcc importedCFile1.c importedCFile2.c mainCode.cu -o maincode
但是我在导入的 C 文件中得到了很多对我的函数的“ undefined reference ”。
要包含我正在使用的 C 文件:
extern "C" {
#include "importedCFile1.h"
#include "importedCFile2.h"
}
“importedCFile1.c”使用了一些在“importedCFile2.c”和“mainCode.cu”中声明的函数和变量。像这样:
extern int **se; // Variables from mainCode
extern int *n;
extern int numNodes;
extern int *getVector(int n); // Function from mainCode
extern int iRand(int high); // Function from importedCFile2
这个函数是 undefined reference 的原因。我应该怎么办?
此外,如何添加 C 代码所需的标志,例如 -lrt
、O3
、lm
和 墙
??
编辑:您可以在此处找到问题的简化示例:
https://github.com/mvnarvaezt/cuda/tree/master/minimalExample
如果您使用 gcc 编译 mainCode.c 和 importedCFile.c,它工作正常。如果您使用 nvcc 编译 mainCode.cu 和 importedCFile.c,您将获得对 anExample()(importedCFile.c 中的函数)的 undefined reference 。
并且您注释了导入 importedCFile.c 的 header 以及对它可以找到的 anExampled() 函数的调用。
最佳答案
您的问题是 importedFile.c 中的 C 代码试图回调 mainCode.cu 中的 C++ 函数。
为了可以从 C 调用,C++ 函数必须具有 C 链接。将 getVector()
声明为
extern "C" int *getVector(int n) {
在 mainCode.cu 中,您的示例可以正常编译。
关于c - 如何使用 C 头文件和 CUDA 代码编译 C 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42656841/