Search code examples
cgccnetbeansheader-filesnetbeans-8.1

Can't resolve an identifier issue in NetBeans


I am trying to setup NetBeans 8.1 Beta for the first time to run my C codes. It seems like I can't resolve an unknown identifier issue! The versions are as below:

enter image description here

Following screenshot is from the main code:

enter image description here

Despite the error, code gets compiled successfully. To my understanding I have introduced the include folder to NetBeans (see below) but it looks like I am doing something wrong because the problem still persists.

enter image description here

I re-parsed the project as advised here and manually added include directory to my project properties.

enter image description here

But still no success. What else do I need to do?


Solution

  • This is actually a rather fascinating little historical quirk of C that I suspect you've run into. Basically what's happening is that Netbeans parses through only the included header files to figure out what functions have been declared. Since you haven't included the header for sleep (unistd.h), Netbeans is not aware of it and is thus confused.

    This now prompts the question of how in the world this compiles then. Well, that's where it gets interesting. It turns out in C, there are implicit function declarations. In other words, if you use a function without declaring it, the compiler will just keep on trucking and assume that it takes arguments of whatever type you gave it and that it returns an int.

    By luck, it turns out the real version of sleep is compatible for linking with this implicit version, thus when linking against the default libraries happens, you're getting lucky and it's finding sleep.

    Note: The warning from Netbeans is correct. You've happened into a "it works for you, but it's not guaranteed to work" situation (welcome to C!), and you should try your best to avoid these. The most immediate step you can take with this situation is to crank up the warnings.

    With the proper warning levels, you would see something like this:

    test.c: In function 'main':
    test.c:4:2: warning: implicit declaration of function 'sleep' [-Wimplicit-function-declaration]
      sleep(5);
      ^
    

    Which would subsequently clue you in that you need to #include <unistd.h>.


    tl;dr: Add #include <unistd.h> and crank up your warnings (something like -Wall -Wextra at a minimum), whatever the Netbeans way of doing that is.