C++ error: ‘char8_t’ was not declared in this scope
The error 'char8_t' was not declared in this scope
occurs in C++ when the program attempts to use the char8_t
type without the necessary C++20 standard enabled or in an older compiler that does not support C++20. The char8_t
type was introduced in C++20 as a distinct type for UTF-8 character literals and strings, and using it without proper configuration leads to this error.
This tutorial explains why this error occurs, how to resolve it, and provides examples with solutions.
Why This Error Occurs
The following are some of the reasons why this error can occur.
- The
char8_t
type is introduced in the C++20 standard. If your compiler is not set to use C++20, thechar8_t
type will not be recognized. - Using an older compiler that does not support the C++20 standard can also cause this error.
- In some cases, even with a modern compiler, the
char8_t
type might be disabled if the standard version is not explicitly specified.
How to Resolve the Error
The following are the possible solutions to resolve this error.
- Ensure that you are using a compiler that supports C++20. Popular compilers like GCC (>=9.1), Clang (>=10), and MSVC (>=2019) support C++20.
- Explicitly enable the C++20 standard in your compiler settings or during compilation: For GCC or Clang, use the
-std=c++20
flag:g++ -std=c++20 -o program program.cpp
- Check your build system or IDE configuration and set the language standard to C++20.
- Update your compiler to the latest version if it does not support C++20.
Examples
Example 1: Program Using char8_t
Without Proper Configuration
This program demonstrates the use of char8_t
without enabling C++20.
#include <iostream>
using namespace std;
int main() {
char8_t ch = u8'A'; // UTF-8 character
cout << ch << endl;
return 0;
}
Error Output:
error: 'char8_t' was not declared in this scope
Solution:
- Enable C++20 by compiling the program with the
-std=c++20
flag:
g++ -std=c++20 -o program program.cpp
Example 2: Correctly Configured Program
This program demonstrates the proper use of char8_t
with the correct C++20 standard enabled.
#include <iostream>
using namespace std;
int main() {
char8_t ch = u8'A'; // UTF-8 character
cout << (char)ch << endl; // Cast to char for output
return 0;
}
Output:
A
Explanation:
- The
char8_t
type is correctly recognized because C++20 is enabled. - The variable
ch
is assigned a UTF-8 character, and the cast tochar
ensures compatibility withstd::cout
.
Key Points to Remember about char8_t data type
char8_t
is a data type introduced in C++20 for handling UTF-8 encoded characters.- Using
char8_t
requires enabling the C++20 standard in your compiler. - Ensure your compiler supports C++20, and use the appropriate flag (
-std=c++20
) during compilation. - Update to the latest version of your compiler if it does not support C++20 features.