Home > Enterprise >  How to configure g as the default compiler in Mac OS (M1)
How to configure g as the default compiler in Mac OS (M1)

Time:01-09

So, I wanted to use some header files native to GNU C :

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

I read that in MacOS, gcc and g are both linked to clang. So, we had to install the gcc using homebrew and use that. But after installing gcc using homebrew. When I run

g   --version

I get

Apple clang version 12.0.5 (clang-1205.0.22.9)
Target: arm64-apple-darwin22.1.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

But running g -12 --version I get:

g  -12 (Homebrew GCC 12.2.0) 12.2.0
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

My VSCode runs g (Apple One) to compile C/C files. For the goal I wanted to accomplish at the start, I read that we need to have the g (installed using homebrew) do the compiling.

So, I ran the following commands:

cd /opt/homebrew/bin
ls -s g  -12 g  

But now, even when I compile the following code:

#include <iostream>
int main()
{
  std::cout << 1;
}

I get the following error:

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:39,
                 from test.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.

Now, removing the link using rm g reverts back to my original configuration. But that configuration can't run the headers I requested at the start. Is there any way to solve this?

Most of the above have mostly been taken from here. But I didn't find any solution. But, I have seen people using the same and getting successful.

EDIT: I found a website where there was a solution. It was to compile not using g . Rather use

g  -12 --sysroot=$(xcrun --show-sdk-path)

When I used this, it solved the problem. Can someone explain why this happened?

CodePudding user response:

The header error likely indicates the g you installed via Homebrew may not be compatible with the Apple Xcode version installed in the macos system directories.

The solution is probably to reinstall one or both packages.

EDIT: g -12 --sysroot=$(xcrun --show-sdk-path) changes the search path for system header includes from the default (which was probably set when homebrew installed g ) to the one provided by the Xcode SDK currently installed.

  • Related