Matt
Matt

Reputation: 20796

Included files from standard directories can silently replace existing macros?

Create the file /usr/local/include/define_x.h with the single line:

#define X "/usr/local/include"

The following program foo.cpp compiles and runs fine with no warnings:

#include <iostream>

#define X "local"
#include <define_x.h>

int main()
{
  std::cout << "X = " << X << std::endl;
  return 0;
}

Output: X = /usr/local/include

Now swap lines 3 and 4:

#include <iostream>

#include <define_x.h>
#define X "local"

int main()
{
  std::cout << "X = " << X << std::endl;
  return 0;
}

Now the output is X = local as expected, but now there is a compiler warning:

foo.cpp:4: warning: "X" redefined
 #define X "local"

In file included from foo.cpp:3:
/usr/local/include/define_x.h:1: note: this is the location of the previous definition
 #define X "/usr/local/include"

Question: Why is there is no warning in the first version?

Both were compiled with gcc 8.2.1: g++ foo.cpp.

It seems it has something to do with placing files in the standard /usr/include or /usr/local/include directories, as placing them either in the current directory or another found via -I doesn't produce this effect.

Upvotes: 2

Views: 42

Answers (1)

harper
harper

Reputation: 13690

System header files often cannot be written in strictly conforming C. They may change some preprocessor macros several times like is this example:

#define FOO 0
#ifdef BAR
#define FOO 1
#endif

It would be annoying to have a warning for all these changes. Therefore the warning is not issued for system header files.

Your code line

#include <define_x.h>

declares the header file to a system header file. You should get a different result if you use

#include "define_x.h"

Upvotes: 1

Related Questions