c++gcc

Friend extern "С" function with enum return type


I have to interface with a С function, but this code doesn't compile.

// c_enum.h
#pragma once

typedef enum { val1 = 0 } c_style_enum_t;
c_style_enum_t c_func();
// my_class.hpp
#pragma once

extern "С" {
#include "c_enum.h"
}

class my_class {
public:
private:
friend c_style_enum_t ::c_func();
};

Gcc prints an errror:

 error: 'enum c_style_enum ' is not a class or namespace
  142 |     friend c_style_enum ::c_func();
error: ISO C++ forbids declaration of 'c_func' with no type [-fpermissive]

When return type of c_func() is int or some other than enum type this wokrs

How to make this work?


Solution

  • Allowing for your friend declaration of a "C" function in the global namespace to work while the "C" function co-exists with a potential c_func residing in the same namespace as my_class, this may be an option:

    friend ::c_style_enum_t(::c_func());
    

    Demo

    Note: This works even without the ambiguity that a c_func in my_class's namespace brings too.