Loose-Info.com
Last Update 2020/09/17
TOP - 各種テスト - gcc - -xオプションの各種言語指定 - -x c

-x c
コンパイラへ供給するファイルの言語を明示的に指定
c : Cソースファイル

テスト概要

その1
言語指定オプション「-x c」によるCソースファイルのコンパイル
PASS コンパイル終了・実行ファイル生成

その2
言語指定オプション「-x c」によるC++ソースファイルのコンパイル
FAIL -xオプションが優先され、Cソースファイルとしてコンパイルされ、エラーにより終了

実行環境

GCC-8.2.0
GNU C Library 2.28
GNU Binutils 2.31.1


コード例・出力内容中の表記

・実行例中の太字表記部分は、コマンドなどの入力された文字列を示します。
・「」や「...」の着色省略表記は、 実際のソースコードや出力内容などを省略加工した部分を示します。

使用ファイル

各例共通

sample.h
/* -x オプション動作確認用ヘッダファイル */ #ifndef SAMPLE_H #define SAMPLE_H #define TEST_FLG 1 struct Samp { int nsamp1; int nsamp2; }; int sampFunc(struct Samp s); #endif /* SAMPLE_H */

sample.c
/* -x オプション動作確認用ソースファイル sample.c */ #include "sample.h" int sampFunc(struct Samp s) { return s.nsamp1 + s.nsamp2 + TEST_FLG; }

main.c
/* -x オプション動作確認用ソースファイル main.c */ #include "sample.h" #include <stdio.h> int main(void) { struct Samp smp; smp.nsamp1 = 1; smp.nsamp2 = 2; int n = sampFunc(smp); printf("n = %d\n", n); printf("TEST_FLG = %d\n", TEST_FLG); return 0; }

その1

言語指定オプション「-x c」によるCソースファイルのコンパイル

コンパイル実行
$ ls -l total 12 -rw-r--r-- 1 ****** ******** 282 *** ** **:** main.c -rw-r--r-- 1 ****** ******** 166 *** ** **:** sample.c -rw-r--r-- 1 ****** ******** 215 *** ** **:** sample.h $ gcc -v -x c sample.c main.c Using built-in specs. COLLECT_GCC=gcc /usr/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/cc1 -quiet -v sample.c ... -o /tmp/ccGLaZP8.s ^^^ sample.cのコンパイル as -v --64 -o /tmp/ccRCQZka.o /tmp/ccGLaZP8.s <--- アセンブル /usr/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/cc1 -quiet -v main.c ... -o /tmp/ccGLaZP8.s ^^^ main.cのコンパイル as -v --64 -o /tmp/cciqNlYb.o /tmp/ccGLaZP8.s <--- アセンブル /usr/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/collect2 ... /tmp/ccRCQZka.o /tmp/cciqNlYb.o ... <--- リンク COLLECT_GCC_OPTIONS='-v' '-mtune=generic' '-march=x86-64' $ ls -l total 32 -rwxr-xr-x 1 ****** ******** 18392 *** ** **:** a.out <--- 作成された実行ファイル -rw-r--r-- 1 ****** ******** 282 *** ** **:** main.c -rw-r--r-- 1 ****** ******** 166 *** ** **:** sample.c -rw-r--r-- 1 ****** ******** 215 *** ** **:** sample.h $ ./a.out n = 4 TEST_FLG = 1 $

その2

言語指定オプション「-x c」によるC++ソースファイルのコンパイル

sample.cpp
/* -x オプション動作確認用ソースファイル sample.cpp */ #include <iostream> int main() { std::cout << "-x オプション動作確認用ソースファイル sample.cpp\n"; return 0; }

コンパイル結果
$ gcc -v -x c sample.cpp -lstdc++ <--- -lstdc++は必要なライブラリ指定 Using built-in specs. COLLECT_GCC=gcc /usr/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/cc1 -quiet -v sample.cpp ... -o /tmp/ccTgOvfO.s ^^^ -xオプションが優先され、Cソースファイルとしてコンパイル sample.cpp:3:10: fatal error: iostream: No such file or directory <--- ライブラリインクルード時のエラー #include <iostream> ^~~~~~~~~~ compilation terminated. <--- エラーにより終了