Skip to content

Instantly share code, notes, and snippets.

@sturmer
Last active December 29, 2015 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturmer/7713293 to your computer and use it in GitHub Desktop.
Save sturmer/7713293 to your computer and use it in GitHub Desktop.
This gist represents the provider module, as described in my post titled "Write an Interface between your program and a Shared Object"
// Test for the shared object
#include "provider.hpp"
#include <iostream>
int main()
{
Provider p;
std::string surname("Wilkes");
std::cout << "Wilkes, " << p.GetResource(surname) << '\n';
return 0;
}
provider_name := provider
.PHONY: all
all: main
%.o: %.cpp
g++ -Wall -Werror -fPIC -c $<
.PHONY: $(provider_name)
$(provider_name): provider.o resource.o
g++ -shared -Wl,-soname,lib$@.so.1 -o lib$@.so.1.0 $^
ln -sf lib$@.so.1.0 lib$@.so.1
ln -sf lib$@.so.1 lib$@.so
main.o: main.cpp
g++ -g -Wall -Werror -c $<
main: main.o $(provider_name)
g++ $< -L. -l$(provider_name) -o $@
clean:
rm -f *.o lib$(provider_name).so* main
love:
@echo "...not war!"
#include "provider.hpp"
#include "resource.hpp"
#include <iostream>
Provider::Provider() : r_(new Resource())
{
std::clog << "Provider::Provider()\n";
}
std::string Provider::GetResource(const std::string& name)
{
std::clog << "Provider::GetResource()\n";
return r_->GetName(name);
}
#ifndef PROVIDER_HPP
#define PROVIDER_HPP
#include <string>
class Resource;
class Provider {
Resource* r_;
public:
Provider();
std::string GetResource(const std::string& name);
};
#endif // PROVIDER_HPP
#include "resource.hpp"
#include <map>
#include <string>
#include <exception>
#include <stdexcept>
#include <iostream>
using std::map;
using std::string;
using std::out_of_range;
using std::exception;
using std::cerr;
using std::clog;
Resource::Resource()
{
clog << "Resource::Resource()\n";
dict_["Lovelace"] = "Ada";
dict_["Wilkes"] = "Mary Allen";
dict_["Liskov"] = "Barbara";
}
std::string Resource::GetName(const std::string& surname)
{
clog << "Resource::GetName(surname=" << surname << ")\n";
string res;
try {
res = dict_.at(surname);
} catch (const out_of_range& oor) {
cerr << "Element not in map:\n" << surname << '\n';
throw;
} catch (const exception& ex) {
cerr << "Unknown exception!\n" << ex.what();
throw;
}
clog << "res = [" << res << "]\n";
return res;
}
#ifndef RESOURCE_HPP
#define RESOURCE_HPP
#include <map>
#include <string>
using std::map;
using std::string;
class Resource {
map<string, string> dict_;
public:
Resource();
std::string GetName(const std::string& surname);
};
#endif // RESOURCE_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment