Connecting C++ and Postgresql

1.1k views Asked by At

I'm trying to connect C++ to Postgres.

I recently installed libpqxx with Homebrew as follows:

brew install libpqxx

Then I made it with: make DatabaseTest on the file DatabaseTest.cpp.

I ran the following simple program and got a strange error that I'm not sure what to do with...

#include <iostream>
#include <pqxx/pqxx>

int main(int, char *argv[])
{
  pqxx::connection c("dbname=company user=accounting");
}

I run make and it's telling me the linker fails, which doesn't make a ton of sense to me...any ideas what might be happening here? Apologies if this is simple, been a while since I've done C++!

  "pqxx::connection_base::init()", referenced from:
      pqxx::basic_connection<pqxx::connect_direct>::basic_connection(char const*) in DatabaseTest-bdc916.o
  "pqxx::connection_base::close()", referenced from:
      pqxx::basic_connection<pqxx::connect_direct>::~basic_connection() in DatabaseTest-bdc916.o
  "pqxx::connection_base::connection_base(pqxx::connectionpolicy&)", referenced from:
      pqxx::basic_connection<pqxx::connect_direct>::basic_connection(char const*) in DatabaseTest-bdc916.o
  "pqxx::connectionpolicy::connectionpolicy(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)", referenced from:
      pqxx::connect_direct::connect_direct(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) in DatabaseTest-bdc916.o
  "pqxx::connectionpolicy::~connectionpolicy()", referenced from:
      pqxx::connect_direct::~connect_direct() in DatabaseTest-bdc916.o
  "vtable for pqxx::connect_direct", referenced from:
      pqxx::connect_direct::connect_direct(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) in DatabaseTest-bdc916.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [DatabaseTest] Error 1
1

There are 1 answers

0
HSchmale On BEST ANSWER

You need a makefile and you need to include your linker flag for pqxx. On my linux box the linker flag is -lpqxx. See my example makefile below.

CXXFLAGS := 
LDFLAGS  := -lpqxx

# Executable output command
$(EXE): $(OBJECTS)
    $(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ $^

# build rule for c++ files
%.o: %.cpp
    $(CXX) -c $(CXXFLAGS) -o $@ $<

When you just invoke make from the command line it just builds the file using the standard commands available for that file. That means it does no linking and it does not run optimization on it.