[英]Linux g++ compiling
我是Linux编程的新手,并在终端中进行编译。 我有三个文件:
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
进行编译, 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。 也许我应该用其他命令来做到这一点?
更新:我已经更新了代码,这是错误的。 :)现在可以了!
尝试运行这个
g++ -Wall -Werror main.cpp sql.cpp -lsqlite3 -o sqlite
这将编译您的sql.cpp文件并将其链接到可执行文件。
您有多个输入文件,它们将全部形成一个二进制文件。
通常的方法(对于大量文件可以很好地缩放)是将每个源文件编译成二进制目标文件,然后将所有目标文件链接到最终的二进制文件中。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.