Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function that returns 'auto' cannot be used before it is defined

Tags:

c++

function

auto

I have a DLL project created in visual c++ and a CLR project. In my DLL project I exported a function with 'auto' type.

staff.h

extern "C" STAFFS_API auto GetStaffMap();

and if staff.cpp it has a std::map return type.

std::map<int, std::string> staffMap;
auto GetStaffMap() 
{
  return staffMap;
}

Now in my CLR application, I call this function:

#include <map>
#include "Staff.h"
std::map<int, std::string> staffMap = Staffs::GetStaffMap();

And when I compile the program, it has an error that says:

C3779 'Staffs::GetStaffMap': a function that returns 'auto' cannot be used before it is defined.

UPDATE

I tried, staff.h

extern "C" STAFFS_API auto GetStaffMap() -> std::map<int, std::string>;

staff.cpp

extern "C" auto GetStaffMap() -> std::map<int, std::string> {
  return staffMap;
}

but still have compile error:

Error   C2526   'GetStaffMap': C linkage function cannot return C++ class 'std::map<int,std::string,std::less<int>,std::allocator<std::pair<const _Kty,_Ty>>>'  AmsCppRest  c:\users\laptop-attendance\source\repos\amscpprest\amscpprest\staff.h

Error   C2556   'std::map<int,std::string,std::less<int>,std::allocator<std::pair<const _Kty,_Ty>>> Staffs::GetStaffMap(void)': overloaded function differs only by return type from 'void Staffs::GetStaffMap(void)'   AmsCppRest  c:\users\laptop-attendance\source\repos\amscpprest\amscpprest\staff.cpp

Error  C2371 'Staffs::GetStaffMap': redefinition; different basic types
like image 688
noyruto88 Avatar asked Feb 17 '26 03:02

noyruto88


2 Answers

auto does not delay finding out the return type of the function. It just makes the compiler look at the implementation to find out what it is automatically. You will have to manually declare the return type in the header since the code that includes the header has to know what the return type is.

like image 169
N00byEdge Avatar answered Feb 19 '26 17:02

N00byEdge


You should declare a returned type so a compiler knows it.

// Declaration
extern "C" STAFFS_API auto GetStaffMap() -> std::map<int, std::string>;

// Definition
extern "C" auto GetStaffMap() -> std::map<int, std::string>
{
  return staffMap;
}
like image 29
273K Avatar answered Feb 19 '26 16:02

273K