Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC preprocessor macro and "#pragma GCC unroll"

Is there another mechanism to get the GCC preprocessor to do this:

#define LIMIT  16
#pragma GCC unroll LIMIT
for (size_t ii = 0; ii < LIMIT; ++ii) {
  ...

That code hits an error:

/path/to/my/file.c:100:20 error: 'LIMIT' undeclared (first use in this function)
  100 | #pragma GCC unroll LIMIT
      |                    ^~~~~

gcc documentation says that this wants an integer constant expression specifying the unrolling factor. I believe that my macro is an "integer constant expression", but...

My compiler is: riscv64-unknown-elf-gcc (g2ee5e430018) 12.2.0.

like image 807
Lance E.T. Compte Avatar asked Oct 29 '25 02:10

Lance E.T. Compte


2 Answers

const and constexpr (in case you can use C++) seems to work (tested with gcc 13.2 on https://godbolt.org/).

const int x = 5;
#pragma GCC unroll x
for (std::size_t ii = 0; ii < x; ++ii) {
like image 127
arch Avatar answered Oct 31 '25 17:10

arch


Instead of the #pragma directive, the _Pragma operator can be used. It is a bit tricky to get the argument expanded correctly, but this should work for both C and C++ (see example on godbolt.org):

#define STRING(V) #V
#define MAKE_PRAGMA(S) _Pragma(S)
#define UNROLL(N) MAKE_PRAGMA(STRING(GCC unroll N))

#define LIMIT 16
...
UNROLL(LIMIT)
for (size_t ii = 0; ii < LIMIT; ++ii) {
  ...
}
like image 25
nielsen Avatar answered Oct 31 '25 17:10

nielsen



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!