10

This is the first time I am trying to use ATLAS. I am not able to link it properly. Here is a very simple sgemm program:

...
#include <cblas.h>


const int M=10;
const int N=8;
const int K=5;

int main()
{
    float *A = new float[M*K];
    float *B = new float[K*N];
    float *C = new float[M*N];

    // Initialize A and B

    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1.0, A, K, B, N, 0.0, C, N);

        ...
}

When I compile it on a linux platform with standard ATLAS installation, it gives linking error:

g++ test.c -lblas -lcblas -latlas -llapack
/tmp/cc1Gu7sr.o: In function `main':
test.c:(.text+0x29e): undefined reference to `cblas_sgemm(CBLAS_ORDER, CBLAS_TRANSPOSE, CBLAS_TRANSPOSE, int, int, int, float, float const*, int, float const*, int, float, float*, int)'
collect2: ld returned 1 exit status

As you can see, I have tried giving different combination of libraries but didn't help. What am I doing wrong?

usman
  • 1,285
  • 1
  • 14
  • 25

2 Answers2

13

You need

extern "C"
{
   #include <cblas.h>
}

because you compile with g++.

Or you could even do

#ifdef __cplusplus
extern "C"
{
#endif
   #include <cblas.h>
#ifdef __cplusplus
}
#endif

to be able to compile as C also.

When you compile in C++, names are expected to be mangled. But since cblas is compiled in C, the exported symbols don't have mangled names. So you have to instruct the compiler to look for C-style symbols.

nandhp
  • 4,680
  • 2
  • 30
  • 42
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • Likely to be the case, but I'm surprised that `` doesn't already have this guard. – Stephen Canon May 28 '12 at 14:31
  • Thanks. I didn't thought about that as its quite common to have this guard now a days in libraries. Anyways, just doing extern "C" made it work. – usman May 28 '12 at 14:36
  • This solution is needed also when using ``AMD-BLIS`` (the blas library of AMD) inside a program compiled with ``g++``. One needs to use the ``extern`` keyword when including ``"cblas.h"``, otherwise a link-time error (no references to function ...) appears ! – velenos14 Aug 30 '23 at 08:25
2

Be careful about the code. It's "C", not C. So, the code finally is

#ifdef __cplusplus
extern "C"
{
#endif //__cplusplus
   #include <cblas.h>
#ifdef __cplusplus
}
#endif //__cplusplus
Sebas
  • 21
  • 1