How to `use mymodule, only: mysymbol` in C++

In Fortran we can import specific symbols with the use statement. For example,

File 1:

module mymodule
  implicit none
  integer, parameter :: age = 29 !! years 
end module

File 2:

module myothermodule
  implicit none
contains
  subroutine dostuff()
    use mymodule, only: age
    print*,age
  end subroutine
end module

The great thing about the use mymodule, only: age syntax is that you are able to very explicit about what is being imported and what should be brought into scope.

Is it possible to do similar explicit importing in C++? This does not seem very possible using header files, because whenever you use #include "myheader.h", you are copy-pasting the contents of the heading into a cpp file. I’ve seem some examples for C++ modules, but it isn’t clear whether you can do explicit imports.

1 Like

You can do something similar with namespaces. Put your code into a namespace in myheader.h, then include the header file. Only the name space top level symbol is “imported” and then you can use it to access more entities. I think C++ modules also allow something similar, but I have not used them yet.

1 Like

C++20 (and C++23) standard revisions for C++ does not have anything like the Fortran language ONLY clause with USE and IMPORT statements, if that is your question.

1 Like

C++ did not get a module system until C++20. The modules system is still not completely implemented in any compiler AFAIK. Even if the support was there, I don’t think there is a way to only import a specific item from a module in C++, but I haven’t tried very hard since the compiler support isn’t available.

So that leaves you with old-school headers. You can use namespaces, as has already been suggested, or split stuff up into separate headers.

1 Like