cmbedtls

Linking to mbedtls libraries


I have simple application that uses mbedtls. I got errors below while compile it:

Starting build...

/usr/bin/g++ -fdiagnostics-color=always -g /home/g/projects/aes2/AES_generate.c -o /home/g/projects/aes2/AES_generate -lmbedtls

/usr/bin/ld: /tmp/ccvPvJJH.o: in function `main':
/home/g/projects/aes2/AES_generate.c:19: undefined reference to `mbedtls_entropy_init'
/usr/bin/ld: /home/g/projects/aes2/AES_generate.c:21: undefined reference to `mbedtls_ctr_drbg_init'
/usr/bin/ld: /home/g/projects/aes2/AES_generate.c:23: undefined reference to `mbedtls_entropy_func'
/usr/bin/ld: /home/g/projects/aes2/AES_generate.c:23: undefined reference to `mbedtls_ctr_drbg_seed'
/usr/bin/ld: /home/g/projects/aes2/AES_generate.c:30: undefined reference to `mbedtls_ctr_drbg_random'
collect2: error: ld returned 1 exit status

How to fix that? Should I link to other libraries?

Program:

#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include <string.h>
#include <stdio.h>

#if !defined(MBEDTLS_PSA_CRYPTO_C)
define MBEDTLS_PSA_CRYPTO_C
#endif

mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_entropy_context entropy;
unsigned char key[32];

char const *pers = "aes generate key";
int ret;

int main()
{
    mbedtls_entropy_init(&entropy);

    mbedtls_ctr_drbg_init(&ctr_drbg);

    if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
                                     (unsigned char *)pers, strlen(pers))) != 0)
    {
        printf(" failed\n ! mbedtls_ctr_drbg_init returned -0x%04x\n", -ret);
        return 0;
    }

    if ((ret = mbedtls_ctr_drbg_random(&ctr_drbg, key, 32)) != 0)
    {
        printf(" failed\n ! mbedtls_ctr_drbg_random returned -0x%04x\n", -ret);
        return 0;
    }

    // printf() displays the string inside quotation
    printf("Hello, World!");
    return 0;
}

Solution

  • According to https://github.com/Mbed-TLS/mbedtls#Compiling you should compile with -lmbedtls -lmbedx509 -lmbedcrypto. The following command should compile the example.

    g++ -fdiagnostics-color=always -g /home/g/projects/aes2/AES_generate.c -o /home/g/projects/aes2/AES_generate -lmbedtls -lmbedx509 -lmbedcrypto