erbal
erbal

Reputation: 727

Linux g++ compiling

I'm new to programming on linux, and compiling in the terminal. I have three files:

sql.h

#ifndef SQL_H
#define SQL_H

#include "sqlite3.h"
#include <string>

class sqlite{
    
private:
    sqlite3 *db;
    sqlite3 *statement;
    
public:
    sqlite(const char* filename);
    void create_table();
};


#endif

sql.cpp

  #include "sql.h"
#include <iostream>

sqlite::sqlite(const char* filename){
    if((sqlite3_open_v2(filename, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL)) == SQLITE_OK) //fájl létrehozása
        std::cout << "Database has been created successfully!" << std::endl;
    
    else{
        std::cout << "Oops, something went wrong, please try again!" << std::endl;  
    }
}   


void sqlite::create_table(/*const std::string &tableName, const std::string &columnNames*/){

    //std::string command = "CREATE TABLE " + tableName + columnNames;
    sqlite3_prepare_v2(db, "CREATE TABLE a (a INTEGER, b INTEGER)", -1, &statement, NULL);
    sqlite3_step(statement);
    sqlite3_finalize(statement);
    sqlite3_close(db);

}

main.cpp

#include "sql.h"
#include <string>
int main(){
    
    sqlite s = sqlite("database.db");
    s.create_table();
    return 0;
}

And if I try to compile it with the command g++ -Wall -Werror main.cpp -lsqlite3 -o sqlite_program, I got the errors:

/tmp/ccKtrrtg.o: In function `main':
main.cpp:(.text+0x15): undefined reference to `sqlite::sqlite(char const*)'
main.cpp:(.text+0x21): undefined reference to `sqlite::create_table()'

This is the first time, I try to compile a cpp with a custom header. Maybe I should do that with a different command?

update: I've updated the code, it was buggy. :) Now it works!

Upvotes: 0

Views: 500

Answers (2)

uml&#228;ute
uml&#228;ute

Reputation: 31374

you have multiple input files, which will all form a single binary.

the usual way (which scales well for larger number of files) is to compile each source-file into a binary object file, and then link all the object files into the final binary.

g++ -Wall -Werror -o main.o -c main.cpp 
g++ -Wall -Werror -o sql.o  -c sql.cpp
g++               -o sqlite    main.o sql.o -lsqlite3

Upvotes: 4

austin
austin

Reputation: 5876

Try to run this

g++ -Wall -Werror main.cpp sql.cpp -lsqlite3 -o sqlite

This will compile your sql.cpp file and link it to the executable.

Upvotes: 4

Related Questions