0

I am trying to see how to embed sql code in a C program, but I have an issue I am not able to understand when I compile this code :

#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>


MYSQL *mysql;
MYSQL_RES *results;
MYSQL_ROW record;


int main() {
 mysql = mysql_init(NULL);

 if (mysql == NULL) {
    fprintf(stderr, "%s\n", mysql_error(mysql));
    return 1;
}

if (mysql_real_connect(mysql, "localhost", "root", "PassWord",
     NULL, 0, NULL, 0) == NULL) {
    fprintf(stderr, "%s\n", mysql_error(mysql));
    mysql_close(mysql);
    return 1;
}

mysql_query(mysql, "SHOW DATABASES");

return 0;
}

this is what the compiler tell me when I compile it :

clang++ -g -c testSql.cc
clang++ testSql.o -o testSql
/usr/bin/ld: testSql.o: in function `main':
/home/antoine/Documenti/L3/Information Management II/code/testSql.cc:12: undefined reference to `mysql_init'
/usr/bin/ld: /home/antoine/Documenti/L3/Information Management II/code/testSql.cc:15: undefined reference to `mysql_error'
/usr/bin/ld: /home/antoine/Documenti/L3/Information Management II/code/testSql.cc:19: undefined reference to `mysql_real_connect'
/usr/bin/ld: /home/antoine/Documenti/L3/Information Management II/code/testSql.cc:21: undefined reference to `mysql_error'
/usr/bin/ld: /home/antoine/Documenti/L3/Information Management II/code/testSql.cc:22: undefined reference to `mysql_close'
/usr/bin/ld: /home/antoine/Documenti/L3/Information Management II/code/testSql.cc:26: undefined reference to `mysql_query'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [Makefile:25: testSql] Errore 1

I have check in the mysql.h file, those function are implemented, so I do not understand why I have this "undifined reference" error, do any onehave an idea on the origin of this error ?

Antoine
  • 71
  • 1
  • 5
  • You need to tell the compiler where the file with the pre-compiled code for MySQL is, something like `clang++ ... -lmysql`; which the compiler will (hopefully) interpret as "look for libmysql.so" in the pre-defined place for libraries – pmg Nov 15 '20 at 16:57
  • At compile time you provide the definitions of the functions by including mysql.h. You must then provide the mysql libraries at link time to provide the code. – stark Nov 15 '20 at 16:57
  • When I googled "undefined reference to mysql_init" I found lot's of answers. Does not any of those help? – klutt Nov 15 '20 at 16:59
  • This will probably help: https://stackoverflow.com/q/10970356/6699433 – klutt Nov 15 '20 at 17:01

1 Answers1

1

Thank you all for the answer. I had to provide a linker in my compilation. I am now compiling with

clang++ -g -c testSql.cc
clang++ testSql.o -o testSql `mysql_config --cflags --libs`

instead of

clang++ -g -c testSql.cc
clang++ testSql.o -o testSql

and it compile correctly. Thank you !

Antoine
  • 71
  • 1
  • 5