Home > Mobile >  Is there a way to detect compiler -fxxxx flags in C code in clang?
Is there a way to detect compiler -fxxxx flags in C code in clang?

Time:10-01

Is there a way to detect compiler -fxxxx flags in C code in clang?

I don't want to store the whole command line in binary, I want to test an individual option.

I want it to provide compilation error or warning if some flag is specified to avoid the code crashing at runtime.

CodePudding user response:

There is no good way of detecting the presence of the flag in C code.

The compiler does not communicate the presence of this flag to the code.

You could write some code that changes behavior based on the presence of the flag, but doing so is very fragile, and not guaranteed to actually work. Intentionally introducing UB into your program is not a particularly good idea. But if you want to do it, it would be something along these lines:

void mark_nonnull(__attribute__((nonnull)) int* p) {}
bool deletes_checks_2(int* p) __attribute__((noinline)) {
  mark_nonnull(p);
  if (p) return true;
  else return false;
}
bool deletes_checks() { return deletes_checks_2(nullptr); }

A better idea is to intercept this at the build system level. You could add a rule that compiles a test file to LLVM IR similar to this: https://reviews.llvm.org/differential/changeset/?ref=1123266 And then you check the resulting IR if the checks are there and abort the build if they aren't.

  • Related