S.S. Anne
S.S. Anne

Reputation: 15576

How do I declare the main() entry point of a program without specifying all arguments in C++?

In C, I can do this to have an unspecified number of arguments in a function:

#include <elf.h>
#include <stddef.h>
#include <stdlib.h>

extern char **__environ;

int __libc_start_main
(
int (*main)(),
int argc,
char **argv
)
{
    int ret;
    Elf32_auxv_t *auxv;
    size_t aux[38];

    /* ... */

    exit(main(argc, argv, __environ, aux));
}

However, when doing this in C++, the compiler emits this error:

test.c: In function ‘int __libc_start_main(int (*)(), int, char**)’:
test.c:21:45: error: too many arguments to function
         exit(main(argc, argv, __environ, aux));
                                             ^

How do I do this in C++?

I understand that the C/C++ standards don't allow this, but I'm currently writing an implementation of the standard C library.

Upvotes: 0

Views: 160

Answers (2)

melpomene
melpomene

Reputation: 85767

The short answer is: You don't.

In C++ all functions have a prototype; there is no such thing as an "unspecified number of arguments".

If you want to call main as main(argc, argv, __environ, aux), you need to declare it as int (*main)(int, char **, char **, void *) or similar.

Upvotes: 3

Radosław Cybulski
Radosław Cybulski

Reputation: 2992

Try either:

void foo(...);

or

template <typename ... ARGS> void foo(ARGS && ... args) { ... body }

First option is the same as void foo() (little known C language fact). First option requires some sort of additional argument (for example printf(char *, ...), where first argument allows function to detect, how to parse following arguments).

Second option requires you to commit to a function body somewhere in a header.

Upvotes: 2

Related Questions