3

Im trying to use libsodium, ive installed the librarys and trying to make the simplests of tests, when making the project using Makefile there are no probkems but when using CLion and Cmake i get "undefined reference to `sodium_init'"

Im working on Ubuntu 18.04. I found the reason for the error was the need to link to add the -lsodium flag to the linking (adding the flag makes a normal Makefile work) as i searched the web for ways to link to an external library using CMake or in CLion i found many solutions that did not work, including :

  • add_link_options(-lsodium)
  • set (CMAKE_STATIC_LINKER_FLAGS "-lsodium")

this is the code im trying to compile:

#include <stdio.h>
#include <sodium.h>

int main() 
{
    if (sodium_init() < 0)
    {
        printf("sodium init error");
    }
    __uint32_t rand = randombytes_random();
    printf("hello %d, this is a random number \n", &rand);
    return 0;
}

The full error message in CLion looks like this :

MakeFiles/TestC.dir/main.c.o: In function `main':
/home/--username--/Projects/TestC/main.c:7: undefined reference to `sodium_init'
collect2: error: ld returned 1 exit status
CMakeFiles/TestC.dir/build.make:83: recipe for target 'TestC' failed
make[3]: *** [TestC] Error 1
CMakeFiles/Makefile2:72: recipe for target 'CMakeFiles/TestC.dir/all' failed
make[2]: *** [CMakeFiles/TestC.dir/all] Error 2
CMakeFiles/Makefile2:84: recipe for target 'CMakeFiles/TestC.dir/rule' failed
make[1]: *** [CMakeFiles/TestC.dir/rule] Error 2
Makefile:118: recipe for target 'TestC' failed
make: *** [TestC] Error 2

EDIT: Ive solved the problem, after looking at - https://stackoverflow.com/a/43136754/7276240 I added the following line to my CMakeLists.txt: target_link_libraries(TestC libsodium.a) TestC being the name of the executable.

  • I see this is marked as a duplicate, but I'm certainly glad this exists. I had the exact same issue, down the the same library. As I am new to C, I don't think the linked duplicate would have caught my attention. It is this post that lead to me solving my problem, not the post that this is allegedly a duplicate of. I wish OP would answer his or her own question in the answer section instead of editing the question, so that others could find this solution more easily. – Joshua Schlichting Nov 26 '19 at 22:30

1 Answers1

2

You can use the usual find_package() or find_library() CMake commands and link it with target_link_libraries(). If you don't want to specify the path manually, there already is a Findsodium.cmake in the official repository. Here is one random example of a CMakeLists.txt found on Github.