Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does _GLIBCXX_DEBUG have to be set in first line?

Tags:

c++

gcc

g++

I am setting debug mode in gcc in the following useless program:

#define _GLIBCXX_DEBUG 1
#include <vector>
#include <iostream>
using namespace std;
int main() {
    vector<int> v{1,2,3};
    for(int i=0; i<100000000000000;i++)
    cout<<v[i];
}

and the program let's me know that my index is going out of bound. However, if I flip the ordering of the first two lines, I get no such error message (#include before #define). Why is this? Is there a way to toggle debug mode on another line in the program (without compiler flags)? I am asking because I am solving problems on Leetcode.com where I can't pass compiler flags or modify the first line of the problem.

like image 224
user3586940 Avatar asked Dec 12 '25 01:12

user3586940


1 Answers

Why does debug mode have to be set in first line?

Because it is the standard library headers which are affected by the macro. If you include the headers before, then the included definitions will not have seen the macro definition. Consider following example, and imagine that it is a function definition included from a standard header:

#define _GLIBCXX_DEBUG 1

inline void foo() {
#ifdef _GLIBCXX_DEBUG
    std::cout  << "debug mode is enabled";
#else
    std::cout  << "debug mode is not enabled";
#endif
}

versus:

inline void foo() {
#ifdef _GLIBCXX_DEBUG
    std::cout  << "debug mode is enabled";
#else
    std::cout  << "debug mode is not enabled";
#endif
}

#define _GLIBCXX_DEBUG 1

Is there a way to toggle debug mode on another line in the program (without compiler flags)?

Not after including the standard headers.

In this case, you could use std::vector::at instead of the subscript operator. It will diagnose out of bounds access even without debug mode.

like image 113
eerorika Avatar answered Dec 14 '25 13:12

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!