我不熟悉在 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 + columnNames;
sqlite3_prepare_v2(db, "CREATE TABLE a (a INTEGER, b INTEGER)", -1, &statement, NULL);
sqlite3_step(statement);
sqlite3_finalize(statement);
sqlite3_close(db);
}
主要.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。也许我应该用不同的命令来做到这一点?
更新:我已经更新了代码,它有问题。 :) 现在可以了!
最佳答案
您有多个输入文件,它们都将形成一个二进制文件。
通常的方法(适用于更大数量的文件)是将每个源文件编译成二进制目标文件,然后将所有目标文件链接到最终的二进制文件。
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
关于c++ - Linux g++ 编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17797203/