Finding out executable location from a c program

Christiaan Hofman cmhofman at gmail.com
Mon Nov 19 08:51:58 PST 2007


On 19 Nov 2007, at 5:37 PM, Paul Sargent wrote:

>
> On 19 Nov 2007, at 16:12, I. Savant wrote:
>
>>>   I would need to find out the directory where the current  
>>> executable
>>> resides to find some stuff whose location I know relative to the
>>> executable location.
>>
>> The first argument ( argv[0] ) is the path to your executable.
>
> Not true. Argv[0] is the first argument given on the command line  
> when your code was invoked. This might be a full path, or it might  
> be just the executable name.
>
> #include <stdio.h>
>
> int main(int argc, char** argv) {
>   printf("Arg 0 is %s\n", argv[0]);
>   return 0;
> }
>
> Compiled and then placed into my path.
>
> Dr-Stupid:~ pauls$ /Users/pauls/bin/a.out
> Arg 0 is /Users/pauls/bin/a.out
> Dr-Stupid:~ pauls$ bin/a.out
> Arg 0 is bin/a.out
> Dr-Stupid:~ pauls$ a.out
> Arg 0 is a.out
>
> There's no guaranteed consistency there, unless you know how it'll  
> be invoked.
>

It can even be the location of a symlink if called that way.

> I can't think of a way of doing it. It's normal practise to put  
> support files in a location like /usr/local/lib or similar rather  
> than with the executable on Unix. On a Mac the solution is normally  
> to package it inside the app bundle and use the API to access that.

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

Christiaan



More information about the MacOSX-dev mailing list