1

I have c++ code to connect to and use mysql:

#include <iostream>
#include <mysql/mysql.h>

using namespace std;

MYSQL *connection, mysql;
MYSQL_RES *result;
MYSQL_ROW row;
int query_state;

int main() {
mysql_init(&mysql);

connection = mysql_real_connect(&mysql,"localhost","root","pass","cpp_data",0,0,0);
if (connection == NULL) {
cout << mysql_error(&mysql) << endl;
return 1;
}
return 0;
}

When I compile, I get test.cpp:(.text+0x11): undefined reference to 'mysql_init' and the same error for mysql_real_connect and mysql_error.

I have tried gcc -o test -L/usr/lib/mysql -lmysqlclient test.cpp, but this give me the following errors:

test.cpp:(.text+0x7a): undefined reference to `std::cout'
test.cpp:(.text+0x7f): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
test.cpp:(.text+0x87): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)' etc.

I checked mysql.h and the definition of mysql_real_connect is:

MYSQL *     STDCALL mysql_real_connect(MYSQL *mysql, const char *host,
                       const char *user,
                       const char *passwd,
                       const char *db,
                       unsigned int port,
                       const char *unix_socket,
                       unsigned long clientflag);

I have no problem when I don't use these mysql functions. Is there another option to solve this problem?

Gaffi
  • 4,307
  • 8
  • 43
  • 73
Akın Yılmaz
  • 300
  • 5
  • 18

1 Answers1

2

You need to compile and link C++ code with g++, not gcc. Otherwise the C++ standard libraries will not get linked properly.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • so g++ -o test -L/usr/lib/mysql -lmysqlclient test.cpp is actually a solution for this problem? – Akın Yılmaz Jan 15 '12 at 13:02
  • For the undefined symbols, yes. (Though you should put the `-lmysqlclient` at the end of that line, after `test.cpp`.) – Mat Jan 15 '12 at 13:03