Within extern "C" { }
the macro __cplusplus
is still defined. When I want to include the C version of mpi.h
in the header of my library which is dynamically load this will not work as mpi.h
still finds __cplusplus
and will still load like it was opened by C++.
#undef __cplusplus
works with gcc. But I do not want to rely on this.
So how to write a C++ program that
- uses the C++ version of mpi and
- is linked against a C-library that uses the C-Version of mpi (where #include <mpi.h>
appears already in the header?
Example code:
library.h:
#ifdef __cplusplus
extern "C" {
#endif
#include <mpi.h>
void library_do(MPI_Comm comm);
#ifdef __cplusplus
}
#endif
program.cpp:
#include <library.h>
#include <mpi.h>
int main() {
MPI::Init();
// do some mpi C++ calls...
library_do(MPI::COMM_WORLD);
MPI::Finalize();
}
In case somebody wants to play the example here the library.c:
#include <stdio.h>
#include "library.h"
void library_do(MPI_Comm comm)
{
int rank;
MPI_Comm_rank(comm, &rank);
printf("MPI Rank: %d", rank);
}
And to compile everything I try with
mpicc -shared library.c -o lib.so
mpicxx program.cpp -l lib.so
__cplusplus
is defined when you are compiling translation unit as C++ code.extern "C" { }
does not make code inside compile as Cmpi.h
still finds__cplusplus
and will still load like it was opened by C++. If__cplusplus
was defined at compile time, and you didn't improperly define it yourself in C code, the library is being opened by C++ code.#undef __cplusplus
is Easter egging - you are blindly changing things you don't understand trying to fix something.