Repository navigation
Description
The usual argc/argv signature requires familiarity some C idioms that don't really have broad influence on C++. An alternative signature could allow new learners to not be bogged down by the dubious char** and \0 termination, and would instead provide them with a clearer, more familiar data type, that would be less error and abuse-prone. Ideally it would only take a single argument, args, which would be a standard list container, holding some number of arguments. Perhaps main : (args: std::vector<std::string_view>) -> int.
Will your feature suggestion eliminate X% of security vulnerabilities of a given kind in current C++ code?
I've seen some wild forms of argument parsing out there that abuse argc. The percentage would definitely be small, but I'm sure there are people out there misusing argc enough to have allowed a memory safety bugs to slip in.
Will your feature suggestion automate or eliminate X% of current C++ guidance literature?
It's largely agreed that passing a length and a C array is bad practice when writing your own functions, but you don't get to dictate the signature of main. Requiring main to follow an idiom that is otherwise frowned upon (and in a place that every C++ programmer is bound to come across!) raises a lot of questions about why things are this way, and why it's a bad idea to use a signature like main's elsewhere in your code. If main took something a little more idiomatic, those conversations can be kicked down the road until much later, instead of requiring they be addressed while trying to write a "Hello, world!"
Some references:
- Jason Turner recently did a whole video that basically ended with the advice "you should probably be constructing a
std::vector<std::string_view>immediately, and then only using that. - The SerenityOS project has a header file which can be included in any individual program that lets you write a
serenity_mainfunction with a nicer type signature, instead of writing the usualmainfunction.
Describe alternatives you've considered.
Some potential types that could be used for args
std::array<_>std::vector<_>_<std::string>_<std::string_view>
Activity
[-][SUGGESTION] Support for a "`main `v2" signature[/-][+][SUGGESTION] Support for a "`main` v2" signature[/+]hsutter commentedon Mar 1, 2023
Thanks, and thanks again to everyone else who has made this suggestion in past issues. This has been on my mind as well.
Yes, there's a safety aspect to this. Just as importantly, there's a simplicity aspect: Simplifying C++ includes addressing the things, even little things, that are constant annoyances and sources of friction and just distractions because we keep having to talk about them (and in many but not all cases have to teach them). That this keeps coming up shows that this is one of those things.
I've already started implementing this a couple of times, and backed it out only because
string_viewisn't guaranteed to be null-terminated. But I don't think that should hold this back anymore... after all, thesestring_views will be null-terminated because of how we got them.With the above checkin, the following works:
There can now be a single-parameter form of global
mainthat defaults to deduced type (you can write: _but you don't have to), and the type will be deduced tovector<string_view>. You can name the parameter whatever you want, but I likeargs... :)If the programmer tries to write something like
main: (inout x)ormain: (x: int), they'll get this error:Thanks again, everyone!
aslilac commentedon Mar 1, 2023
Sorry for the duplicate! I tried to search for if someone had already suggested this and must've missed it! But very happy to see this change. :) Thanks Herb!
filipsajdak commentedon Mar 8, 2023
@hsutter, one question regarding the new
main()syntax there are libraries that expect to processargcandargvarguments, e.g., command line options parsers. In my project I am using cxxopts and previously the following code worked:Maybe we should provide a way to get argc & argv for some cases? I think it should not be the default, but for the sake of
I think we should provide it.
I am asking here to clarify if I should post a bug report or if is it a feature that I need to learn to live with.
filipsajdak commentedon Mar 8, 2023
I have realized that I can rewrite it to:
It will generate the following cpp1 code:
The question is if using implementation details is the solution we want to support.
hsutter commentedon Mar 8, 2023
That's a good point...
The named parameter
argsgives you easy access to the value ofargcby askingargs.ssize(), but not toargvif you really really want an array of raw pointers.But because under the covers cppfront generates the standard signature, you actually do have access to both
argcandargvdirectly with those names. So this works right now:That said, I didn't actually realize that until you asked the question, so thanks! And I like it... it encourages the right thing (the visible named parameter is safe and the thing you naturally use), but writing a named parameter also makes
argcandargvimplicitly available and that strikes me as a useful convenience (i.e., a feature, not a bug). Bonus: And they are guaranteed to have those familiar names, whereas today those two parameters can be called whatever the programmer wants to name them, those names are just a convention today.Speaking of which... one thing that I haven't done, but have sometimes considered, is requiring the name of the single parameter to actually be
args(right now you can name it anything). Requiring it to be the nameargsremoves a degree of freedom, but one that doesn't matter, so it arguably could be a "constraints are liberating" benefit in the sense of directing creativity toward the directions that matter, and it would guarantee the visual consistency (args,argc,argv).hsutter commentedon Mar 8, 2023
Ah, racing replies -- you saw it too. Yes, I think it's important to guarantee those names' availability because you gave a great motivating example showing that it's part of full compatibility with all existing C and C++ libraries, which rely on
argcandargv.What do you think of requiring the single-main-parameter name to be
args?filipsajdak commentedon Mar 8, 2023
Most of us were using
argcandargvby convention. My first choice, nevertheless, would beargs. So, from that point of view, requiring the name to be exactlyargsshould not harm and would be aligned with what most of us will do. That will reduce complexity by reducing name variation.filipsajdak commentedon Mar 8, 2023
Last quick thought before going to sleep. Maybe we can do something like this: https://godbolt.org/z/s7bq33MT7
argswill behave like before but will give access toargc&argvwithout hiding them in implementation details.filipsajdak commentedon Mar 8, 2023
Array requires the size to be known at compile time which is not the case for the
main()function.AbhinavK00 commentedon Mar 8, 2023
Sorry for my replies, realised they weren't correct so deleted both of them.
hsutter commentedon Mar 8, 2023
@filipsajdak I like your implementation strategy, and I'll pursue the direction of providing
args.argcandargs.argv, and deliberately uglifying the actual main parameter names so that they shouldn't be used directly. Thanks!(Fun fact: Generating the main parameter name
__argccauses MSVC to generate an executable that crashes when you try to use that name to access the int. That's what can happen when you stray into the implementer's namespace... so I'll use something likeargc_andargv_as the uglified names instead.)8 remaining items
jcanizales commentedon Mar 9, 2023
It's the other way around, so should be OK 🙂
at()in the STL containers throws if the key isn't present.operator[]()instead would give you a default-constructed value, which in the case of reading environmental variables seems like the right choice.Commit the last few evenings' changes
gregmarr commentedon Mar 9, 2023
Only if the value in the dictionary value is something like an optional string view, as it needs to preserve the difference between null and an empty string.
std::getenv:jcanizales commentedon Mar 9, 2023
Is that a thing people do with env variables? 😩
gregmarr commentedon Mar 9, 2023
Yes, sometimes it is enough to have a variable set, without any particular content.
Sarcasm commentedon Mar 10, 2023
I wonder if allocation is really needed for
args, maybevectorcould be replaced by some similarly styled API that do not require an owning container,std::span<std::string_view>could work right?argvis mutable I think, it's not uncommon to see some frameworks takeargvas a parameter, extract the framework options and return an updatedargv, e.g. Qt, instantiating aQApplication(int &argc, char **argv)will extract some general Qt parameters like-style Fusionand updateargcandargvaccordingly, so the application can just parse the remaining arguments as it pleases : https://doc.qt.io/qt-6/qapplication.html#QApplicationA useful property of
char **environthat getenv/setenv do not provide, is that enumerating all the environment variables. This is sometimes useful, e.g. when spawning subprocesses.gregmarr commentedon Mar 10, 2023
No, you need something to own the
std::string_viewobjects that are created.Sarcasm commentedon Mar 11, 2023
Right! 👍
I knew I was missing something...
filipsajdak commentedon Mar 11, 2023
It could be omitted using ranges. When ranges will be available on all platforms we can work on that further.
filipsajdak commentedon Apr 17, 2023
Because my apple-clang-14 has just provided support for ranges, I prepared a PR that uses ranges to avoid allocating std::vector - see: #380
hsutter commentedon Apr 19, 2023
Thanks! I worry about that newness though -- is it worth discarding compatibility with last month's Apple Clang to save a single allocation?
(will repeat this comment on the PR)
filipsajdak commentedon Apr 19, 2023
Thanks. Sorry for the trouble.
Allow single-argument global `main` that gets a `vector<string_view>`, …
Commit the last few evenings' changes
Allow single-argument global `main` that gets a `vector<string_view>`, …