cmacosgccclang

Use GCC on Mac instead of Clang


I have a Mac with macOS v13.5.1 (Ventura) (Intel microprocessor). I need to use GCC instead of Clang on Mac. How can I can do it?

Now I have something like this on my Mac:

cd ~
gcc -v

Output:

Apple clang version 14.0.3 (clang-1403.0.22.14.1)
Target: x86_64-apple-darwin22.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

And:

cd /usr/bin
gcc -v

Output:

Apple clang version 14.0.3 (clang-1403.0.22.14.1)
Target: x86_64-apple-darwin22.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

Here is the code, which will compile fine. But on Linux, with GCC, it will raise a float-conversion error.

#include <stdio.h>
#include <math.h>

#define ERROR_OK 0
#define ERROR_IO 1
#define ERROR_RANGE 2
#define EPSILON 0.00001

int are_points_collinear(float x1, float y1, float x2, float y2, float x3, float y3)
{
    return fabs((y3 - y2) * (x2 - x1) - (y2 - y1) * (x3 - x2)) < EPSILON;
}

float area(float x_a, float y_a, float x_b, float y_b, float x_c, float y_c)
{
    double s;
    s = 0.5 * fabs((x_b - x_a) * (y_c - y_a) - (x_c - x_a) * (y_b - y_a));
    return s;
}

int main(void)
{
    double x_a, y_a, x_b, y_b, x_c, y_c;
    double s;

    printf("Enter coordinates of point A (x, y): ");
    if (scanf("%lf %lf", &x_a, &y_a) != 2)
        return ERROR_IO;

    printf("Enter coordinates of point B (x, y): ");
    if (scanf("%lf %lf", &x_b, &y_b) != 2)
        return ERROR_IO;

    printf("Enter coordinates of point C (x, y): ");
    if (scanf("%lf %lf", &x_c, &y_c) != 2)
        return ERROR_IO;

    if (are_points_collinear(x_a, y_a, x_b, y_b, x_c, y_c))
        return ERROR_RANGE;

    s = area(x_a, y_a, x_b, y_b, x_c, y_c);
    printf("S = %lf\n", s);

    return ERROR_OK;
}

I compile with

gcc -std=c99 -Wall -Werror -Wpedantic -Wfloat-equal -Wfloat-conversion -Wextra -o app.exe main.c -lm

Solution

  • The -Wfloat-conversion option gives a warning if you convert a double to a float due to a possible loss of precision, and -Werror converts all warnings to errors. This warning or error is being triggered because your functions accept float arguments but you're passing in double arguments.

    You typically shouldn't use float instead of double unless you have a specific reason for doing so, so change all float declarations to double.

    int are_points_collinear(double x1, double y1, double x2, double y2, double x3, double y3)
    {
        return fabs((y3 - y2) * (x2 - x1) - (y2 - y1) * (x3 - x2)) < EPSILON;
    }
     
    double area(double x_a, double y_a, double x_b, double y_b, double x_c, double y_c)
    {
        double s;
        s = 0.5 * fabs((x_b - x_a) * (y_c - y_a) - (x_c - x_a) * (y_b - y_a));
        return s;
    }