LoginSignup
2
0

macOS環境にて、gccコンパイルを実行する方法

Last updated at Posted at 2022-12-11

本記事について

macOS環境にて、gccコンパイルを実行する方法について記述します。 

実行環境 

・macOS Ventura 13.0.1
・Homebrew GCC 12.2.0

問題点

下記のiostreamライブラリを使用したCソースをgccコンパイラでコンパイルしようとすると、fatal error(=致命的なエラー)が発生してしまう。 

■Cソース

  1 #include <iostream>
  2 using namespace std;
  3 
  4 int main(void){
  5 
  6         string name1, name2;
  7 
  8         name1 = "Satoshi ";
  9         cin >> name2;
 10         cout << "Hello, " + name1 + " " + name2 << endl;
 11 
 12         return 0;
 13 }

■実行結果 
「ヘッダーファイルwchar.hは存在しません。」という感じの致命的エラーが発生します。

% gcc -g main.cpp
In file included from /opt/homebrew/Cellar/gcc/12.2.0/include/c++/12/bits/postypes.h:40,
                 from /opt/homebrew/Cellar/gcc/12.2.0/include/c++/12/iosfwd:40,
                 from /opt/homebrew/Cellar/gcc/12.2.0/include/c++/12/ios:38,
                 from /opt/homebrew/Cellar/gcc/12.2.0/include/c++/12/ostream:38,
                 from /opt/homebrew/Cellar/gcc/12.2.0/include/c++/12/iostream:3,
                 from main.cpp:1:
/opt/homebrew/Cellar/gcc/12.2.0/include/c++/12/cwchar:44:10: fatal error: wchar.h: No such file or directory
   44 | #include <wchar.h>
      |          ^~~~~~~~~
compilation terminated.

 

解決方法 

コンパイル時に下記のオプションを加えることにより、 上記のような致命的なエラーが発生しなくなります。

% g++ --sysroot=$(xcrun --show-sdk-path) main.cpp

やはり、xcrunコマンドを用いてSDKヘッダーパスをsysrootオプションに指定する必要があるみたいだ…

% xcrun --show-sdk-path
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk
% cd `xcrun --show-sdk-path`
% pwd
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk
% find ./ -name 'wchar.h'   
.//usr/include/c++/v1/__support/solaris/wchar.h
.//usr/include/c++/v1/wchar.h
.//usr/include/wchar.h

これでgccコンパイラはwchar.hを参照することが出来る。

2
0
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
2
0