2013-07-22 152 views
0

我是新手,在linux上编程,并在终端编译。我有三个文件:Linux g ++编译

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 + culomnNames; 
    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; 
} 

如果我尝试用命令g++ -Wall -Werror main.cpp -lsqlite3 -o sqlite_program编译它,我得到了错误:

/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()' 

这是第一次,我尝试用自定义标题编译cpp。也许我应该用不同的命令来做到这一点?

更新:我更新了代码,它是越野车。 :)现在它的作品!

+0

编译器并不神奇,你必须告诉它你正在编译什么(或者在这种情况下是链接)。 – 2013-07-22 21:00:46

+0

[Undefined reference C++]的可能重复(http://stackoverflow.com/questions/6284720/undefined-reference-c) – 2013-07-22 21:02:18

回答

4

你有多个输入文件,它们都会形成一个二进制文件。

通常的方式(其为较大的文件的数量很好地扩展)是将每个源文件编译成二进制对象文件,然后所有的对象文件链接到最终的二进制。

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 
+0

第二行给我的错误: https://www.dropbox.com/s/vqg8he8rcuf1736/show.txt?m – erbal

+0

@erbal包括在sql.cpp – Amadeus

+1

@erbal ,那是因为你的代码是越野车;你必须在sql.cpp中包含,'statement'成员的类型应该是'sqlite3_stmt'而不是'sqlite3'等等。 –

4

尝试运行此

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

这将编译你的sql.cpp文件,并将其链接到可执行文件。

+0

(你所错过的是输入文件sql.cpp,它包含了定义) – Sniggerfardimungus

+0

我得到这个错误: sql.cpp:在构造函数'sqlite :: sqlite(const char *)'中: sql.cpp:5:3:error:'cout '不是'std'的成员 sql.cpp:5:61:error:'endl'不是'std'的成员 sql.cpp:8:3:错误:'cout'不是'std' sql.cpp:8:67:error:'endl'不是'std'的成员 sql.cpp:在成员函数'void sqlite :: create_table()'中: .... – erbal

+0

在你的sql.cpp文件(或头文件)中,你需要使用'#include ',它具有'std :: cout'和'std :: endl'的定义。 – austin