How to use the Boost libraries in a C program

Viewed 727

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?

4 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.

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.

Your C project likely compiles fine with a C++ compiler. Use a C++ compiler and then you have access to Boost and all other C++ libraries. That's the kind of transition C++ was initially designed to handle.

Boost can't be used with C as it uses OOP features from C++. It may be technically possible to develop a wrapper for it. Check Developing C wrapper API for Object-Oriented C++ code.

Boost is very C++ oriented, and there isn't any guarantee that even this will work. There's really no point of using Boost in C. Firstly because Boost is mostly for "boosting" OOP (and also for other utility), and secondly because, why not use C++? They are really similar and you can use C standard library with C++ and you can also use procedural programming with C++. So, you better use C++ with C standard library (but I can't give any guarantee that it will work flawlessly) and not use OOP features of C++.

Related