Phil Rosenberg
Phil Rosenberg

Reputation: 1779

variable was not declared in this scope gcc error

I have the following templated function

//This is a very naive implementation, but it will do
template<class T>
T determinant(const std::vector<std::vector<T>> &matrix)
{
    sci::assertThrow(square(matrix), sci::err());
    if (matrix.size() == 1)
        return matrix[0][0];
    else if (matrix.size() == 2)
        return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
    else
    {
        double result = 0;
        std::vector<std::vector<double>> minor(matrix.size() - 1);
        double multiplier = 1.0;
        for (size_t i = 0; i < matrix.size(); ++i)
        {
            for (size_t j = 0; j < minor.size(); ++j)
            {
                if (j < i)
                    minor[j] = matrix[j];
                else
                    minor[j] = matrix[j + 1];
            }
            result += multiplier * matrix[0][i] * sci::determinant(minor);
            multiplier *= -1.0;
        }
        return result;
    }
}

which compiled fine with visual studio 2015, however gcc says

g++ -c -Wall -g -std=c++11 -fPIC -o3 -o build/svector.o svector/svector.cpp
In file included from svector/svector_internal.h:6:0,
                 from svector/svector.cpp:1:
svector/../include/svector/dep/svector.h: In function 'T sci::determinant(const std::vector<std::vector<T> >&)':
svector/../include/svector/dep/svector.h:2888:28: error: 'minor' was not declared in this scope
     for (size_t j = 0; j < minor.size(); ++j)
                            ^
svector/../include/svector/dep/svector.h:2895:60: error: 'minor' was not declared in this scope
     result += multiplier * matrix[0][i] * sci::determinant(minor);
                                                            ^

It looks to me like minor is definitely in scope at the point that gcc is complaining about. Can anyone shed any light on the reason for this error?

Upvotes: 0

Views: 3089

Answers (1)

interjay
interjay

Reputation: 110108

sys/sysmacros.h in Glibc contains the macro definitions:

# define major(dev) gnu_dev_major (dev)
# define minor(dev) gnu_dev_minor (dev)

This is probably being included through some system header which you are including.

The parentheses after minor in the variable definition cause the macro invocation, which changes the variable name. The other uses of minor have no parentheses and therefore the macro isn't invoked, which causes minor to reference a nonexistent variable.

You can either rename the minor variable or undefine minor to fix the error.

Upvotes: 5

Related Questions