Reputation: 98
I am hoping to receive some input on an issue I encountered while attempting to learn c++20 modules.
In short, I would like a namespace containing const and/or constexpr variables to be implemented within a module, and import that module into any implementation files applicable.
It works fine with non const / non constexpr variables, however this isn't ideal; I'd like to stick with const and/or constexpr depending on the data types within the namespace.
Please see example below:
// test_module.cpp
module;
#include <string_view>
export module test_module;
export namespace some_useful_ns {
/* produces a compile error when attempting to compile main.cpp */
constexpr std::string_view str_view{"a constexpr string view"};
const char* const chr{"a const char* const"};
/* compiles just fine, but not ideal; prefer const / constexpr
std::string_view str_view{"a non constexpr str view"};
const char* chr{"a const char*"};
*/
}
// main.cpp
#include <iostream>
import test_module;
int main() {
std::cout << some_useful_ns::str_view << std::endl;
std::cout << some_useful_ns::chr << std::endl;
return 0;
}
Compile the two files like below:
g++ -c --std=c++2a -fmodules-ts test_module.cpp
g++ -c --std=c++2a -fmodules-ts main.cpp
g++ main.o test_module.o
Before linking the .o files, I receive the following error when compiling main.cpp like above:
main.cpp: In function ‘int main()’:
main.cpp:6:38: error: ‘str_view’ is not a member of ‘some_useful_ns’
6 | std::cout << some_useful_ns::str_view << std::endl;
| ^~~~~~~~
main.cpp:7:38: error: ‘chr’ is not a member of ‘some_useful_ns’
7 | std::cout << some_useful_ns::chr << std::endl;
|
I find this strange since it works fine when I use a non const / non constexpr like the lines commented out in test_module.cpp. Also, using the const / constexpr works just as expected when using a traditional implementation without modules.
Anyone have a clue as to why I am unable to get this to work successfully with const / constexpr?
In case it helps, I am using gcc (GCC) 11.2.1 20220127
Thanks in advance.
Upvotes: 2
Views: 2238
Reputation: 473916
This seems like a compiler bug.
Normally, const
-qualified variables have internal linkage, and names with internal linkage cannot be exported. However... there's a specific carveout for such variables which are exported. That is, exported const
-qualified variables don't have internal linkage.
Upvotes: 1