Just Because it Compiles, Doesn’t Mean it Works
For unknown reasons, I tried:
usleep(1,000,000); (hey, it was early, don’t laugh)
and it compiled. And usleep was even returning 0 as if it was working. Well, from what I can tell, usleep was only seeing 1. Not sure where the rest of the 0’s went. As I’m sure you know, that needs to be:
usleep(1000000);
My question is why doesn’t the compiler whine about me sending 3 arguments to a C function that only takes 1? I don’t even see a warning. I dug a little deeper. Turns if you want to see the error, you have to #include<unistd.h> (that’s where usleep’s prototype is declared). So why does this even compile? Shouldn’t the compiler want a declaration for usleep before I can use it? Thinking this might be some Xcode magic (hey, I don’t know), I created a very small test program and compiled it with gcc-3.3 on a NetBSD box. The results were the same. The next question was, what if I try call an undefined function? Enter, “tonyrndl(5);”. The file compiles just fine, but it doesn’t link. This is surprising to me. I guess I’ve been living in a world with -Wall on for too long and taken a lot of warnings for granted. Compiling again with -Wall gives a nice:
test.c:6: warning: implicit declaration of function usleep'
test.c:7: warning: implicit declaration of functiontonyrndl'
So the only reason it compiled and linked with usleep is because usleep is in libc so the linker happily found it’s way home.
Thoughts about warnings
I am a fan of warnings. I just set -Wall -Werror in my current Xcode project and it already found a stupid typo. I was calling ‘NSlog’ somewhere where I needed ‘NSLog’ (why that links, I’m not sure). Those are the types of errors that should be caught before you even run your app. Xcode’s default $(WARNING_CFLAGS) is pretty good, and sometimes -Wall -Werror makes you jump through hoops to get something you know is OK just to compile. So it’s a trade off that each project has to decide for itself. Personally, I need -Werror to force me to address each warning. It’s too easy to just ignore the “8 warnings” in the lower corner of Xcode. -Wall seems like a good idea, at least to start with. However, my project is still small, we’ll see how long -Wall -Werror holds.
Note, if you only wanted to catch the example I gave above without -Wall, add -Wimplicit-function-declaration to your projects “Other warning flags” build setting.
Not a problem in C++
Turns out C++ no longer allows implicit declarations. Attempting to explicitly set -Wimplicit-function-declaration for the C++ compiler gives you a compiler error stating it’s an invalid parameter for C++, but valid for C or Obj-C.
Sleep? Wuh?
You should be asking, “why is he calling usleep or any sleep related function at all”? Don’t worry, it was only to test how a thread acted if it slept for a little bit here and there. And yes, I know about NSThread’s:
+ (void)sleepUntilDate:(NSDate *)aDate
but again, this was just a quick and dirty test.
