gcc options: -fsigned-char
A guide to understanding and using the -fsigned-char and -funsigned-char GCC options to control the signedness of plain char.
April 2, 2026
gcc options: -fsigned-char
Reqruies
- Compiler: gcc 2.8 later
컴파일 옵션 없이
결과는
char를 사용한다면, 이 타입은 signed일까요 아니면 unsigned일까요?결과는
architecture와 compiler에 따라 달라집니다.많은 개발자가 보통
하지만 이러한 습관은 아키텍처나 컴파일러 옵션에 따라 예기치 않은 동작을 유발할 수 있으므로 매우 위험합니다.
특히 아키텍처에 독립적인(
char를 signed char라고 생각하고 코드를 작성하곤 합니다.하지만 이러한 습관은 아키텍처나 컴파일러 옵션에 따라 예기치 않은 동작을 유발할 수 있으므로 매우 위험합니다.
특히 아키텍처에 독립적인(
architecture-independent) 코드를 작성해야 한다면 반드시 피해야 할 코딩 습관입니다.GCC 컴파일러에는
char를 signed로 처리할지 unsigned로 처리할지 결정하는 옵션(GCC 문서에서는 C Dialect Options로 분류)이 존재합니다.Options
-fsigned-char, -funsigned-char, -fno-signed-char, -fno-unsigned-char
여러 옵션이 있지만, 결과적으로는 다음 두 가지 의미로 사용됩니다.
char를 signed char로 처리: -fsigned-char, -fno-unsigned-char
char를 unsigned char로 처리: -funsigned-char, -fno-signed-char
매우 단순한 GCC 옵션이며, GCC 문서에도 자세히 설명되어 있습니다.
GCC Documentation
gcc-7.4.0/C-Dialect-OptionsDoc-funsigned-char
Let the type char be unsigned, like unsigned char. Each kind of machine has a default for what char should be. It is either like unsigned char by default or like signed char by default. Ideally, a portable program should always use signed char or unsigned char when it depends on the signedness of an object. But many programs have been written to use plain char and expect it to be signed, or expect it to be unsigned, depending on the machines they were written for. This option, and its inverse, let you make such a program work with the opposite default. The type char is always a distinct type from each of signed char or unsigned char, even though its behavior is always just like one of those two.
이 옵션이 처음 도입된 GCC 버전을 공식 문서에서 정확히 찾지는 못했지만, GCC 2.8.0 릴리즈 코드에서는 이미 포함되어 있는 것을 확인할 수 있습니다.
gcc-2.8.0 toplev.cc
공식 릴리즈 노트에서는 명확한 이력을 찾기 어렵지만,
cpp 전처리기 소스 코드에서는 GCC 3.1 버전에 해당 옵션 파싱이 추가된 것으로 보입니다.gcc-3.1 cppinit.cc
Verification
실제로 옵션이 의도한 대로 동작하는지 코드를 통해 확인해 보겠습니다.
char.cc
Execution result without optionsh
x86_64 환경과 현재 컴파일러에서는 char를 signed char로 처리하고 있습니다.여기에
-funsigned-char 옵션을 추가해 보겠습니다.Execution result with -funsigned-charsh
-funsigned-char 옵션을 추가하여
char가 unsigned char로 사용되는 것을 확인할 수 있습니다.Architecture
각 아키텍처별로
char를 기본적으로 어떻게 처리하는지도 살펴보겠습니다.x86_64 - default signed charbash
aarch64 - default unsigned charbash
mips64 - default signed charbash
ppc - default unsigned charbash
Check with sample code
char가 signed인지 unsigned인지 쉽게 확인할 수 있는 샘플 코드가 있습니다.Simple check codec
Resultsh
Conclusion
대규모 프로젝트에서는 빌드 시스템에 의해 컴파일 옵션이 전역적으로 추가되거나 변경될 수 있으므로, 기본 부호 특성에 의존하면 예기치 않은 버그가 발생할 수 있습니다.
결론적으로 컴파일 옵션에 의존하기보다는, 부호(signed/unsigned) 구분이 중요한 코드에서는
char 대신 signed char 또는 unsigned char를 명시적으로 사용하는 것이 훨씬 안전하고 바람직합니다.