Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do i link wininet library with cmake

This is c++ code to get IP address (main.cpp) (project -> Prueba2 ).

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

std::string real_ip() {

    HINTERNET net = InternetOpen("IP retriever",
                                 INTERNET_OPEN_TYPE_PRECONFIG,
                                 NULL,
                                 NULL,
                                 0);

    HINTERNET conn = InternetOpenUrl(net,
                                     "http://myexternalip.com/raw",
                                     NULL,
                                     0,
                                     INTERNET_FLAG_RELOAD,
                                     0);

    char buffer[4096];
    DWORD read;

    InternetReadFile(conn, buffer, sizeof(buffer)/sizeof(buffer[0]), &read);
    InternetCloseHandle(net);

    return std::string(buffer, read);
}

int main() {
    std::cout << real_ip() << std::endl;
    return 0;
}

CMakeLists.txt file for compiling.

cmake_minimum_required(VERSION 3.22)
project(Prueba2)

set(CMAKE_CXX_STANDARD 20)

add_executable(Prueba2 main.cpp)

I have to link this library but i don’t know how, this error appears. I know how to compile it with g++ adding the library with -lwininet and it works correctly, i’m trying to do it with cmake now. Thank you for your help

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

undefined reference to `__imp_InternetOpenA'
C:\Program Files\JetBrains\CLion 2022.1.3\bin\mingw\bin/ld.exe: C:/Users/JAVIER/CLionProjects/Prueba2/main.cpp:13: undefined reference to `__imp_InternetOpenUrlA'
C:\Program Files\JetBrains\CLion 2022.1.3\bin\mingw\bin/ld.exe: C:/Users/JAVIER/CLionProjects/Prueba2/main.cpp:23: undefined reference to `__imp_InternetReadFile'
C:\Program Files\JetBrains\CLion 2022.1.3\bin\mingw\bin/ld.exe: C:/Users/JAVIER/CLionProjects/Prueba2/main.cpp:24: undefined reference to `__imp_InternetCloseHandle'

>Solution :

You can use target_link_libraries:

...
add_executable(Prueba2 main.cpp)
target_link_libraries(Prueba2 wininet)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading