I run all my C ++ Windows applications on Ubuntu Linux. This application works fine in Visual Studio 2015 on Windows 7. However, it gives an error when running in code blocks on Ubuntu Linux. I have replicated the error message I get using the following simple Person class.
Error message: 'comparePersonAge' was not declared in this scope
Person.h
#ifndef Person_h #define Person_h #include <string> class Person { private: int age; std::string name; public: Person(int a, std::string n) : age(a), name(n) {} int getAge() { return age; } std::string getName() { return name; } inline friend bool comparePersonAge(const Person& p1, const Person& p2) { return p1.age < p2.age; } }; #endif
main.cpp
#include <iostream> #include <algorithm> #include <vector> #include "Person.h" int main() { Person p1(93, "harold"); Person p2(32, "james"); Person p3(67, "tracey"); std::vector<Person> v; v.push_back(p1); v.push_back(p2); v.push_back(p3); std::sort(v.begin(), v.end(), comparePersonAge); std::cout << v[0].getAge() << " " << v[1].getAge() << " " << v[2].getAge() << std::endl; }
On a Windows computer, output: 32 67 93 , as expected. On Linux, the error message is listed above.
Note. . Someone else, the name DJR, discusses this issue in this post: Friend function not declared in this scope error. . However, his explanation is very vague and does not follow his steps.
He's writing:
Previous comment should be read: This is a bug on the Linux side. The code should work as it is written. I have code right now that compiles on the Windows side, and when I switch to the Linux side, I get the same error. Apparently, the compiler that you use on the Linux side does not see / do not use the friend declaration in the header file and therefore gives this error. Just translating the friend function definition / implementation into a C ++ file before using this function (for example, how one could use it when assigning a callback function), this fixed my problem and also solved your problem.
I don't know what it means by moving the friend function definition in the C ++ file until the function is used. What does it mean?