Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is __cplusplus defined within extern "C"

Tags:

c++

c

mpi

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
like image 755
user2722085 Avatar asked Nov 30 '22 21:11

user2722085


1 Answers

__cplusplus will always be defined by the compiler if the compiler is a C++ compiler. extern "C" {} only gives you C linkage so the code inside plays nice with a C compiler.

like image 141
Hatted Rooster Avatar answered Dec 09 '22 11:12

Hatted Rooster