3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C言語としてコンパイルされるか、C++としてコンパイルされるか

Posted at

はじめに

g++ test.c

を実行したときに、C言語としてコンパイルされるかC++としてコンパイルされるかが気になることがあると思います。
こちらの記事によると

C言語では 文字定数(character constant) の型はintです。よって常に sizeof('C') == sizeof(int) となります。

C++:C++言語では 文字リテラル(character literal) の型はcharとなるため、sizeof('C') == sizeof(char)つまりsizeof('C') == 1となります。この違いを利用して「C/C++判定トリック」として紹介されることもあります。

とあります。
これを使ってテストをしてみましょう。

テストコード

test.c/test.cpp
# include<stdio.h>
int main(void){
  printf("%zu\n", sizeof('A'));
  return 0;
}

ソースコードはtest.c/test.cpp共通です。(拡張子だけが違います)
出力が4ならC言語、1ならC++です。
コンパイラはgcc/g++、clang/clang++でテストします。

実行結果

$ gcc test.c 
$ ./a.out
4
$ gcc test.cpp
$ ./a.out
1
$ g++ test.c
$ ./a.out
1
$ g++ test.cpp
$ ./a.out
1
$ clang test.c
$ ./a.out
4
$ clang test.cpp
$ ./a.out
1
$ clang++ test.c
clang: warning: treating 'c' input as 'c++' when in C++ mode, this behavior is deprecated [-Wdeprecated]
$ ./a.out
1
$ clang++ test.cpp
$ ./a.out
1

まとめ

Cコンパイラ(gcc/clang)かつ拡張子が.cの場合のみ、C言語としてコンパイルされるようです。

実行環境

Ubuntu 18.04
gcc/g++ : 7.5.0
clang/clang++ : version 6.0.0-1ubuntu2

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?