0

I have create simple library testlib.c:

char *reverse(char *string)
{
    int len = strlen(string);
    for (int i = 0; i < len / 2; i++)
    {
        char tmp = string[i];
        string[i] = string[len - 1 - i];
        string[len - 1 - i] = tmp;
    }
    return string;
}

Now created shared library:

cc -fPIC -shared -o libtest.so testlib.c -lc
sudo mv libtest.so /usr/local/lib

Now having this cmake project:

.
├── c1
│   └── main.cpp
└── CMakeLists.txt

main.cpp:

#include <iostream>

char *reverse(char*);

int main(int argc, char **argv)
{
    if (argc > 1)
    {
        puts(argv[1]);
        puts(reverse(argv[1]));
    }
}

and finally in CMakeLists.txt:

cmake_minimum_required(VERSION 3.20.0)
project(c1)

add_executable(c1 c1/main.cpp)
include_directories(.)

find_library(TEST_LIBRARY
        NAMES test)
link_libraries(c1 TEST_LIBRARY)

I am getting link error:

main.cpp:(.text+0x3b): undefined reference to `reverse(char*)'

even with the find_library cmake command. So how to make cmake to find local library and link it?

milanHrabos
  • 2,010
  • 3
  • 11
  • 45
  • Correct line which links the executable with the library is `target_link_libraries(c1 ${TEST_LIBRARY})`. See e.g. [that answer](https://stackoverflow.com/a/41909627/3440745). – Tsyvarev Apr 02 '22 at 14:06
  • Still getting link error, after changing it after the provided answer. Now the cmake is: `set(CMAKE_PREFIX_PATH /usr/local/lib)` `find_library(TEST_LIB test)` `link_libraries(c1 ${TEST_LIB})` but still undefined reference – milanHrabos Apr 02 '22 at 14:18
  • Please, read the other code **carefully**. The command is named `target_link_libraries`, not `link_libraries`. – Tsyvarev Apr 02 '22 at 15:01

0 Answers0