Finding out executable location from a c program

Alastair Houghton alastair at alastairs-place.net
Tue Nov 20 04:36:53 PST 2007


On 19 Nov 2007, at 16:51, Christiaan Hofman wrote:

> I also wouldn't know. There should be a way though, as internally  
> NSBundle does.

You can use _NSGetExecutablePath() from <mach-o/dyld.h>.  According to  
the header, it might return the path to a symlink, so you may want to  
use realpath() as well, and you could potentially create a security  
hole if you use this the wrong way.

(I should add that this function is "officially sanctioned" in as much  
as it's used in MoreIsBetter: <http://developer.apple.com/samplecode/MoreIsBetter/listing208.html 
 >; it used to be documented in the NSModule man page, but it looks  
like that no longer exists.)

It's perhaps worth saying though that using the path of your tool is  
generally an evil thing to do.  It's normally best, for command line  
tools, to hard-code paths to any resources they need in the normal  
UNIX places, or to stick them inside an associated application and use  
Launch Services to locate that (you probably want  
LSFindApplicationForInfo()), then use CF or NSBundle to grab  
references to the relevant files from there.

Kind regards,

Alastair.

--
http://alastairs-place.net




More information about the MacOSX-dev mailing list