Search code examples
c++command-line-argumentsprogram-entry-point

Get command line arguments without arguments in main()


One strange thing took my sleep away. .

I have P7 library. It is library for writing logs.

Library contains few examples. Example for C++ looks like:

int main(int i_iArgC, char* i_pArgV[])
{
   // Some code that don't use i_iArgC or i_pArgV
}

But the trick that program handle command line arguments somehow.
I play a little bit to make sure that this main called.
What I do:

  1. Build in debug and set breakpoint on main (to make sure that exactly this main is called)
  2. Changemain(int i_iArgC, char* i_pArgV[]) to main() (To make sure that no one use them)

I have no idea how it possible.

Here is minimal steps you can do to look on it by yourself:

  1. Download P7 code from this page (link at top left)
  2. Unzip archive
  3. Run build.sh (It runs few makefiles in some order)
  4. Execute Cpp_Example from Binaries folder
  5. Execute again Cpp_Example /P7.Help to see that app react to command line arguments.

Solution

  • Most systems allow for getting the command line parameters without relying on main(). On Windows for example, you can use GetCommandLineW().

    The library has non-portable code to do just that in Shared/Platforms/*/PProcess.h. A quick look at Windows_x86/PProcess.h shows that it uses GetCommandLineW() and the same file in Linux_x86/ reads /proc/self/cmdline.