Welcome to HBH! If you had an account on hellboundhacker.org you will need to reset your password using the Lost Password system before you will be able to login.

MySQL + C Problem


chess_rock's Avatar
Member
0 0

Hey there,

I've been recently struggling to program something simple using C and Mysql but i'm having lots of trouble. I've googled up and down, and i can't make the following code work properly:

#include <mysql/mysql.h>

int main(void)
{
      MYSQL con;

      mysql_init(&con);
      if ( mysql_real_connect(&con, "localhost", "user", "pass", "db", 0, NULL, 0) )
      {
            printf("Connected!\n");
            mysql_close(&con);
       }
       else
       {
            printf("Not connected\n");
            printf("Error %d : %s\n", mysql_errno(&con), mysql_error(&con));
       }
}```

I don't really know if the code is wrong or if the mysql library was not correctly installed... So here is the error that appears when i try to compile the program:

```markupgcc -o trem.out trem.c
/tmp/ccORzxsv.o: In function `main':
trem.c:(.text+0x2a): undefined reference to `mysql_init'
trem.c:(.text+0x70): undefined reference to `mysql_real_connect'
trem.c:(.text+0x8e): undefined reference to `mysql_close'
trem.c:(.text+0xaa): undefined reference to `mysql_error'
trem.c:(.text+0xba): undefined reference to `mysql_errno'
collect2: ld returned 1 exit status

I re-installed the library but it seems that it is not the problem. It works when i write a code without a parameter like:

MYSQL con

Can anyone help me please? :)


p4plus2's Avatar
Member
0 0

Try compiling it like this:

gcc -o trem -L/usr/lib/mysql -lmysqlclient trem.c


chess_rock's Avatar
Member
0 0

Thank you a lot! It worked :)

I have one question about all this… Why do i have to compile this way? Because if it worked it means that the library was correctly installed, right? Shouldn't the #include <mysql/mysql.h> solve the problem?


ghost's Avatar
0 0

chess_rock wrote: Thank you a lot! It worked :)

I have one question about all this… Why do i have to compile this way? Because if it worked it means that the library was correctly installed, right? Shouldn't the #include <mysql/mysql.h> solve the problem?

You still need to link against the mysql library, otherwise your program wouldn't know where to find the code for the mysql functions.

Including the header tells GCC what the functions look like (return type, arguments etc), not where the actual code is.