Reputation: 3
I'm trying to make a simple C++ static library to use with a C program. My files are the following.
// strarr.h
#pragma once
#include <stdio.h>
#ifdef __cplusplus
extern "C"
{
#endif
typedef char **str_arr;
str_arr new_str_arr(size_t size);
void del_str_arr(str_arr arr, size_t size);
str_arr resize_str_arr(str_arr arr, size_t arr_size, size_t new_size);
size_t add_str(str_arr arr, size_t index, char *str);
#ifdef __cplusplus
}
#endif
void print_arr(str_arr arr, size_t size);
// strarr.c
#include "strarr.h"
#include <stdlib.h>
str_arr new_str_arr(size_t size)
{
str_arr arr = (str_arr)calloc(size, sizeof(char*));
if (arr == NULL) return NULL;
for (size_t i = 0; i < size; i++)
{
arr[i] = (char*)calloc(1, sizeof(char));
if (arr[i] == NULL) return NULL;
}
return arr;
}
void del_str_arr(str_arr arr, size_t size)
{
for (size_t i = 0; i < size; i++)
{
free(arr[i]);
arr[i] = NULL;
}
free(arr);
arr = NULL;
}
str_arr resize_str_arr(str_arr arr, size_t arr_size, size_t new_size)
{
return NULL;
}
size_t add_str(str_arr arr, size_t index, char* str)
{
return 0;
}
// strarr.cpp
#include "strarr.h"
#include <iostream>
void print_arr(str_arr arr, size_t size)
{
for (size_t i = 0; i < size; i++)
std::cout << i << ": " << arr[i] << std::endl;
}
I'm compiling manually with the following commands
g++ -c strarr.c -o bin/static/strarr.o
g++ -lstdc++ -c strarr.cpp -o bin/static/strarrcpp.o
ar rvs bin/static/libqbb.a bin/static/strarr.o bin/static/strarrcpp.o
I've imported the successfully built library in a C project, but while building it spits out this error.
====================[ Build | all | Debug ]=====================================
C:\Users\AGSoldier\AppData\Local\JetBrains\Toolbox\apps\CLion\ch-0\202.6397.106\bin\cmake\win\bin\cmake.exe --build "D:\AGSoldier\Sidereal Works\Qbb\qbb_test\build" --target all -- -j 3
Scanning dependencies of target qbb_test
[ 50%] Building C object CMakeFiles/qbb_test.dir/main.c.obj
[100%] Linking C executable qbb_test.exe
CMakeFiles\qbb_test.dir/objects.a(main.c.obj): In function `main':
D:/AGSoldier/Sidereal Works/Qbb/qbb_test/main.c:468: undefined reference to `print_arr'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[2]: *** [CMakeFiles\qbb_test.dir\build.make:107: qbb_test.exe] Error 1
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:95: CMakeFiles/qbb_test.dir/all] Error 2
mingw32-make.exe: *** [Makefile:103: all] Error 2
What an I doing wrong? I googled for a few hours without any result.
Upvotes: 0
Views: 101
Reputation: 41
You need to put the declaration
void print_arr(str_arr arr, size_t size);
into the extern C scope if you are going to call that function from a *.c file.
Upvotes: 1