Adding cublas to a c++ code

Greetings. Let’s say that I have two c++ files: first.C and second.C. Normally, I can compile these two files as follows.

icpc -o first first.C second.C

Now, I want to add cublas routines in second.C. How should I proceed? I tried this and failed.

mv second.C

nvcc -c // creates second.o
icpc -c first.C // creates first.o

icpc -o first first.o second.o

Any ideas?

You don’t need to use nvcc at all with CUBLAS. Just import cublas.h into whatever files contain cublas calls, like this:

extern "C" {

#include "cublas.h"


and then compile with your host C++ compiler. In the linking phase, just supply cublas and cudart as libraries to the linker and it should just work.

Not understanding this. For example, let’s say there are two files first.C and second.C where second.C contains cublas calls.

Then add

extern "C" { #include "cublas.h"}

in second.C.

Then g++ -lcublas -lcudart -o main first.C second.C. Right? However, this gives me an error statement stating that cublas.h does not exist.

Btw, I figured out what was wrong with what I did in the original post. I need a -lcublas and it works.

You have to tell the compiler where to find cublas.h using a -I directive (something like -I/somepath/cuda/include). The extern “C” declaration is required to prevent any C++ function name mangling from happening and tell the compiler to use strict C semantics for the function call.

Hmm. The above works but -lcublas doesn’t.

$ g++ -I /somepath/cuda/include -o main main.C

undefined reference to ‘cublasInit’ …

$ g++ -I /somepath/cuda/include -lcublas -o main main.C

/usr/bin/ld: cannot find -lcublas

so I suspect that I have to change the path?

You need to specify both the location ( with -L/usr/local/cuda/lib64 ) and the library name ( -lcublas).
You also need to put these at the end of the command ( the linker resolve left to right).

Assuming that cuda is installed in /usr/local/cuda:

g++ -I/usr/local/cuda/include -o main main.c -L/usr/local/cuda/lib64 -lcublas

You should get familiar with Linux and the gcc toolchain.

I’ve tried this as well (something similar) and doesn’t work. What is the library file name that I’m exactly looking for here?

It is But take the advice offered and spend some time familiarizing yourself with how the build system works. There is a world of pain coming if you don’t and plan on building complex applications.