Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clang-Tidy: Initializing non-local variable with non-const expression depending on uninitialized non-local variable, C pointer reference

Tags:

c

clang-tidy

We have a very simple bit of code which is giving a warning but seems like it should be fine, and runs fine. We understand that in general there may be issues with order of initialisation between compilation units, but in this case we are initialising with a pointer, so don't understand how order can cause a problem, or how any problems might arise with this code. Note that in the real code we have more complex scenario with structs, but code below shows the basic issue.

EDIT: have removed const qualifiers as they don't affect the warning

file1.c

int foo=42;

file2.c

#include <stdio.h>

extern int foo;
// Clang-Tidy: Initializing non-local variable with non-const expression depending on uninitialized non-local variable 'foo'
int *bar=&foo;

int main() {
  printf("%d\n", *bar); // prints '42'
}

Warning is not from gcc but from clang-tidy. To reproduce run:

clang-tidy -checks=* file1.c file2.c
like image 929
jugglingcats Avatar asked Nov 15 '25 04:11

jugglingcats


2 Answers

clang-tidy is warning about something that just is not a problem: whether foo is initialized or not does not make a difference in this initializer where only its address is taken.

Furthermore foo is a global variable, hence it is either statically initialized in the module that defines it or it does not have an initializer and is initialized to 0 by the loader at run time. If the program was compiled as C++, foo might be initialized at runtime, before main is called, potentially by running initializer code, but again this does not make a difference as only its address is used in int *bar = &foo;

You should just disable this warning, as explained by Cameron Tacklind.

like image 137
chqrlie Avatar answered Nov 17 '25 18:11

chqrlie


As others have mentioned, clang-tidy is telling you precisely what is wrong.

In this case, I think the clincher is the first part of the sentence: "Initializing non-local variable ...".

The particular warning will go away if bar is declared (and defined) inside main():

#include <stdio.h>

extern int foo;

int main() {
  int *bar=&foo; // Still warns about const issues

  printf("%d\n", *bar);
}

Alternatively, you can ignore the specific rule for those specific lines pretty easily:

#include <stdio.h>

extern int foo;

// NOLINTNEXTLINE(cppcoreguidelines-interfaces-global-init)
int *bar=&foo;

int main() {
  printf("%d\n", *bar);
}
like image 26
Cameron Tacklind Avatar answered Nov 17 '25 18:11

Cameron Tacklind