1

Consider a C++ function that I want to interface it in C (e.g., int foo()) that takes no input arguments.

The lack of input arguments in C can be expressed as int foo(void);, while int foo() in C means arbitrary number of input arguments.

However, in C++ int foo() means a function that takes no arguments and int foo(void) is considered a C backward compatibility remnant that should be avoided.

Considering the above, what's the most proper?

Option 1:

C header declaration : int foo(void);

C++ file definition : int foo(void) { ... }

Option 2:

C header declaration : int foo();

C++ file definition : int foo() { ... }

Option 3:

C header declaration : int foo(void);

C++ file definition : int foo() { ... }

101010
  • 41,839
  • 11
  • 94
  • 168

2 Answers2

4

OK, we already know the difference between f() and f(void) in C and C++.

Since using f() is bad practice in C (you lose the compiler's ability to compare the function's declaration to its definition, to ensure that it will be called correctly) and you have C linkage for that function, I'd advise to use f(void)

After all, in c++, f(void) was only kept alive to have backwards combatibility with C, which is exactly your use case.


Just a minor correction : It's not arbitrary number of input arguments but unspecified meaning that's there's a serious difference to variadic functions.

Community
  • 1
  • 1
Nikos Athanasiou
  • 29,616
  • 15
  • 87
  • 153
1

I would use:

// Header
#ifdef __cplusplus
extern "C" {
#endif
void foo(void);
#ifdef __cplusplus
}
#endif

And for cpp file:

// in cpp file
extern "C" {
    void foo(void)
    {
        // implementation
    }
}

As we explicitly show that we use C.

Jarod42
  • 203,559
  • 14
  • 181
  • 302