Search code examples
powershellcommand-line-argumentsjavac

How to use command-line argument files for javac on windows?


Here's my working directory:

C:\GitHub\

And under this directory I have:

class\ src\ cmain

and cmain is my argument file.

All my .java source code files are undersrc\

main.java CalcHandler.java

And here's the content ofcmain

-cp .\class\
-sourcepath .\src\
-d .\class\
.\src\main.java

But when I tried compiling src\main.java in PowerShell usingcmain, it is not recognized:

PS C:\GitHub> javac @cmain
Usage: javac <options> <source files>                                                                                   
where possible options include:                                                                                           
-g                         Generate all debugging info                                                                  
-g:none                    Generate no debugging info
....

I tried this in Linux and it worked fine, contents were exactly the same.

What should I do to make it work?

Edit: Apparently this is PowerShell's fault, it worked in command-prompt. But still I'd like to hear from you about how to make it correct in PowerShell.


Solution

  • javac '@cmain'
    

    PowerShell parses arguments to commands, and @cmain means taking the array $cmain and expanding it to one argument per item (splatting). By passing an explicit string you can bypass that automatism.

    Other options:

    javac --% @cmain
    

    This will tell PowerShell to stop parsing arguments after the --% marker and just pass them verbatim to the other program.

    javac `@cmain 
    

    This will escape the @ so its special behavior will not apply.

    Always remember that shell features will need workarounds if you want to pass that syntax to other programs. That's no different than % expanding environment variables in cmd, or most shells tokenizing arguments at spaces and other whitespace. A small utility program that just prints its arguments can come in handy for diagnosing such cases.