2

I am trying to use cblas library to use BLAS. I call cblas function from a custom C function and then link this file to my C++ file. But I get this error

Cfile.o: In function `mm_blas':
Cfile.c:(.text+0xbf): undefined reference to `cblas_dgemv'
collect2: error: ld returned 1 exit status

My Cfile.c

#include <stdio.h>
#include <cblas.h>

void f(double dd[])
{
    int i;
      for (i=0; i<2; ++i)  printf("%5.1f\n", dd[i]);
    printf("\n This is a C code\n");
}

    double m[] = {
  3, 1, 3,
  1, 5, 9,
  2, 6, 5
};

double x[] = {
  -1, -1, 1
};

double y[] = {
  0, 0, 0
};

void mm_blas(double m1[], double m2[], double m3[], int m_size){
  cblas_dgemv(CblasRowMajor, CblasNoTrans, 3, 3, 1.0, m, 3, x, 1, 0.0, y, 1);
}

And main.cpp

#include <iostream>
#include <fstream>
#include <random>
#include <chrono>
#include <time.h>
#include <string>
#include <algorithm>
#include <ostream>

using namespace std;
using namespace std::chrono;

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

    void f(double []);
    void mm_blas(double [], double [], double [], int);
}

void func(void)
{
    std::cout<<"\n being used within C++ code\n";
}

int main(void)
{
    double dd [] = {1,2,3};
    f(dd);
    func();
    return 0;
}

I compile the code with command

gcc -c -lblas Cfile.c -o Cfile.o  && g++ -std=c++11 -lblas -o  myfoobar Cfile.o main.cpp && ./myfoobar

I am on Linux, gcc 4.8. How to solve this problem.

asdfkjasdfjk
  • 3,784
  • 18
  • 64
  • 104

1 Answers1

3

Do this instead:

gcc -c Cfile.c -o Cfile.o  && g++ -std=c++11 -o  myfoobar Cfile.o main.cpp -lblas && ./myfoobar

a) There is no point in passing linkage options (-lblas) to gcc -c ... because -c means don't link.

b) In the linkage sequence, by default, files that require symbol definitions must occur before the ones that provide the definitions. So object files before the libraries that they refer to, else the libraries are ignored and the references are unresolved.

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182