So... I was happily working on a project and then I was going to implement a friend function, which returns an object of the class after generating a random number of arbitrary size. On compilation, it's showing the error undefined reference... blah blah blah
Below is a brief mimic of the actual code/issue...
class Declaration: Random.h
// Random Declarations
#ifndef _RANDOM_H
#define _RANDOM_H
#include <stdint.h>
#include <vector>
#include <ostream>
using uv = std::vector<uint16_t>;
using std::ostream;
using std::size_t;
class Random {
uv data;
public:
friend Random generate(const size_t&);
friend ostream& operator<< (ostream&, const Random&);
};
#endif
class Definition: Random.cpp
// Random Definitions
#include "Random.h"
#include <cstdlib>
Random generate(const size_t& sz) {
Random newRandom;
newRandom.data.resize(sz);
for(auto &x : newRandom.data) {
x = rand();
}
return newRandom;
}
ostream& operator<< (ostream& out, const Random& random) {
if(random.data.empty()) {
out << '0';
} else {
for(auto &x : random.data) {
out << x;
}
}
return out;
}
And here is the main.cpp
#include <iostream>
#include "Random.h"
int main() {
Random r = generate(10U); // <-- This line is throwing the error
std::cout << r << "\n";
}
Error:
PS D:\INT\The Friend Issue> g++ main.cpp Random.cpp
main.cpp: In function 'int main()':
main.cpp:5:28: error: 'generate' was not declared in this scope
Random r = generate(10U);
^
By the way, if I declare the generate in main also then it works.
#include <iostream>
#include "Random.h"
Random generate(const std::size_t&);
int main() {
Random r = generate(10U);
std::cout << r << "\n";
}
No Error
PS D:\INT\The Friend Issue> g++ main.cpp Random.cpp
PS D:\INT\The Friend Issue> .\a.exe
4118467633426500191691572411478293582696224464
Any help would be thankful...