0

I am a c++ beginner, working on a school project. We were given numerous working demo projects performing simple computations for us to understand the basics of CUDA.

Each of these projects has a structure like this:

main.cpp

#include <stdio.h>

// Prototype of function from .cu file
void run_cuda();

int main()
{
    // Function calling
    run_cuda();
    return 0;
}

cuda.cu

#include <cuda.h>
#include <cuda_runtime.h>
#include <stdio.h>

void run_cuda()
{
    ... implementation ...
}

... other functions, kernel function ...

Now what I dont understand is - how can they call the run_cuda() function from main.cpp when they never include any header file (and the header file is not even present in the project directory) or anything else that would tell the main.cpp file where to look for that function at?

At first I thought it might be an error, but every single project (even from multiple sources) has this structure. However when I try to do the same thing with my project, the compilation of main.cpp fails.

main.cpp: undefined reference to `run_cuda'

P. Paul
  • 363
  • 3
  • 17
  • There isn't anything unique or specific to CUDA in your question. The linked duplicate explains why the `undefined reference` error occurs in C/C++ and what to do about it. (The inclusion, or lack of, the header file with the prototypes is not what impacts a "undefined reference" error, which is a *linker* error. A header file does not instruct the linker in any way.) – Robert Crovella Nov 04 '19 at 16:29
  • I now understand that the problem has nothing to do with CUDA, nor with missing header. Still, these answers often provide solutions for something I dont use (i.e. Visual Studio, inline specifier etc.). My problem must be something more simple I think - maybe I use a wrong command to compile my files? I am trying to do this: `nvcc -o cuda.o cuda.cu -c` and then `g++ main.cpp -o main`. Is that a correct approach? – P. Paul Nov 04 '19 at 18:48
  • 1
    1. `nvcc -o cuda.o cuda.cu -c` 2. `g++ -c main.cpp -o main.o` 3. `g++ main.o cuda.o -o main -L/usr/local/cuda/lib64 -lcudart` (assumes standard CUDA install location). Alternatively: `nvcc -o main cuda.cu main.cpp`. There are various questions on the `cuda` tag which discuss all sorts of compilation command nuances. – Robert Crovella Nov 04 '19 at 18:57
  • The linked duplicate starts to discuss the compilation flow, and differentiates between for example what is compilation vs. what is linking. Understanding these key elements will help to give you understanding about how to issue the commands. Without that, you're stuck with understanding a bunch of meaningless and complicated rules. A number of examples are also given in the [nvcc manual](https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html). – Robert Crovella Nov 04 '19 at 19:00

0 Answers0