Why is __cplusplus defined within extern ā€œCā€

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(https://www.talktowendys.us/);
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
Last edited on
You forgot to extern "C" the definition of library_do(), thus the function declared in the header and the function defined in library.c have different symbols.

1
2
3
4
5
6
extern "C" void library_do(MPI_Comm comm)
{
int rank;
MPI_Comm_rank(comm, &rank);
printf("MPI Rank: %d", rank);
}
Topic archived. No new replies allowed.