Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the Boost libraries in a C program

Tags:

c++

c

gcc

boost

I'm working on a project which is written in C, but I would like to use Boost. I have included the Boost libraries in my main file as follows:

#define GNU_SOURCE
#define _GNU_SOURCE
#include <stdlib.h>
#include "initialize.h"
#include <stdio.h>
#include <math.h>
#include <boost/random/linear_congruential.hpp>

I am compiling with gcc -W -Wall -I/usr/local/boost_1_76_0 main.c -o executable -lm -lboost_random.

main.c:8:10: fatal error: iostream: No such file or directory
    8 | #include <iostream>

I guess that the Boost libraries are using <iostream>, but since it's not a C library, I am not sure how to deal with that issue... Should I compile with C++ instead?

like image 250
pulsar_hh Avatar asked Sep 12 '25 07:09

pulsar_hh


2 Answers

Boost is very much a C++ library, and as such can't be used in a C program.

You'll need to use C++ if you want to use Boost.

like image 94
dbush Avatar answered Sep 13 '25 21:09

dbush


Boost is strictly for C++. Even if bits of it compile with a C compiler, there's no guarantee that will always be the case.

One approach would be to build a dll / so in C++ using Boost, exporting functions using C-style linkage.

Then link to that library using C.

like image 32
Bathsheba Avatar answered Sep 13 '25 21:09

Bathsheba