Search code examples
c++mysqlvisual-studio-codeg++mingw

VSCode c++ mysql.h undefined reference to 'mysql_init@4'


I am trying to get C++ to work with mysql.h in VSCode. I have put all of the files (.h, libmysql.lib, ...) in the same folder as my 'main.cpp' file and I have tried executing the program with

g++ main.cpp -I"D:\Projects\New project"

And I keep getting the following error :

c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\user\AppData\Local
\Temp\ccYwlVSu.o:main.cpp:(.text+0x43): undefined reference to `mysql_init@4'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\user\AppData\Local          
\Temp\ccYwlVSu.o:main.cpp:(.text+0x8c): undefined reference to `mysql_real_connect@32'
collect2.exe: error: ld returned 1 exit status

I have read that I need to link properly all of my libraries, which I think I am doing with the '-I' command. What am I missing?

main.cpp

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

int main(){
    MYSQL* conn;
    conn = mysql_init(0);
    conn = mysql_real_connect(conn, "localhost", "root", "", "airlines_db", 0, NULL, 0);

    if(conn){
        std::cout << "Connected" << std::endl;
    } else {
        std::cout << "Not connected" << std::endl;
    }
}

tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "echo",
            "command": "g++",
            "args": [
                "-g", "main.cpp"
            ],
            "group": {
                "kind" : "build",
                "isDefault": true
            }
        }
    ]
}

c_cpp_properties.json

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "C:\\MinGW\\bin\\gcc.exe",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "clang-x86",
            "browse": {
                "path": [
                    "C:\\MinGW\\lib\\gcc\\mingw32\\9.2.0\\include\\c++"
                ]
            }
        }
    ],
    "version": 4
}

Solution

  • I figured it out - there was a -lmysql missing in my command. I have added it and it's all good now!