Dominick Pastore
Dominick Pastore

Reputation: 4435

When mixing C and C++ code, does main() need to be in the C++ part?

I have a C program that I need to interface with a C++ library (ROS). Normally, it's not too difficult to interface C code with C++ code with a wrapper using extern "C" and using the C++ compiler to link, but I've never had to do it where main was in the C portion.

The C++ FAQ indicates that this is a bad thing:

Here are some high points (though some compiler-vendors might not require all these; check with your compiler-vendor’s documentation):

  • You must use your C++ compiler when compiling main() (e.g., for static initialization)

But I see another source saying it should be okay these days:

At one time, most C++ compilers required that function main be compiled by the C++ compiler. That requirement is not common today, ...

Why would it matter whether main is in the C portion or the C++ portion? How much trouble would I be in if I try to link code where it's in the C portion using common linkers today (mainly GCC's and Clang's)?

Upvotes: 6

Views: 386

Answers (1)

Michaël Roy
Michaël Roy

Reputation: 6471

One easy way to work around this is to rename your C main() and call it from a new C++ main()

As in:

// in ypur current C main module

int my_c_main(int argc, char* argv[]) /* renamed, was main() */
{
   /* ... */
]

// in a c++ module...

int main(int argc, char* argv[])
{
    extern "C" int my_c_main(int argc, char* argv[]);

    // if your c main() requires environment variables passed in envp,
    // You can allocate space for strings and an array here and pass
    // the environment variables you'll need, as the third parameter
    // to my_c_main(), or pass environ, if your system has
    // it defined in unistd.h

    return my_c_main(argc, argv);
}

Upvotes: 1

Related Questions