經過幾年時間,我用概念證明回到了C++。我有一個hpp文件,它定義了一個類,一個帶有類方法的cpp文件和一個用於測試的main.cpp。我試圖創建一個運行在它自己的線程中的tcp服務器(只調用一次)。我開始使用同一個cpp文件中的所有代碼,並開始工作,但現在我已經將類和方法放在自己的文件中,因此出現編譯錯誤。C++ 11如何在其他類或源文件中引用類方法
我已經搜索,但沒有找到任何工作。我試過使用extern,'singleton'等方法,這些都會導致各種錯誤消息。我知道我沒有提供正確的方法參考。
tcpserver.hpp
:
#ifndef __TCP_SERVER_HPP_INCLUDED__
#define __TCP_SERVER_HPP_INCLUDED__
#include <string>
class Server {
public:
static void *tcp_server(void * dummy);
static void hello();
static int parseCmd(const char *cmd, char *reply);
static int copystring(char *reply, const char *msg);
private:
};
#endif
tcpserver.cpp
,與類方法作爲存根:
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <cstring> // Needed for memset
#include <sys/socket.h> // Needed for the socket functions
#include <netdb.h> // Needed for the socket functions
#include <string.h>
#include "tcpserver.hpp"
int Server::parseCmd(const char *cmd, char *reply) {
//does stuff
}
int Server::copystring(char *dst, const char *src) {
// does stuff
return (int) ((std::string) dst).length();
}
void Server::hello() {
std::cout << "Server says 'hello'." << std::endl;
}
void *Server::tcp_server(void * dummy) {
const char *port = "5555";
// does a lot of stuff
}
main.cpp
:
#include <iostream>
#include <pthread.h>
#include "tcpserver.hpp"
int main() {
Server server;
server.hello(); // 'Canary' method FIRST ERROR
// Initialize and set thread joinable
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_t serverthread;
int rc;
// **** tcp_server method must be static ****
rc = pthread_create(&serverthread, NULL, server.tcp_server, NULL);
if (rc){
std::cout << "Error:unable to create thread," << rc << std::endl;
exit(-1);
}
std::cout << "Main() started thread." << std::endl;
pthread_attr_destroy(&attr);
void *status;
rc = pthread_join(serverthread, &status);
if (rc){
std::cout << "Error:unable to join," << rc << std::endl;
exit(-1);
}
return 0 ;
}
makefile
:
all : main.o tcpserver.o
g++ -std=c++11 -o tcpserver main.o tcpserver.o
tcpserver.o: tcpserver.cpp tcpserver.hpp
g++ -std=c++11 tcpserver.hpp
main.o : main.cpp tcpserver.hpp
g++ -std=c++11 main.cpp -lpthread
clean:
rm -f tcpserver.o main.o tcpserver
你收到了哪些錯誤信息?另外,'__TCP_SERVER_HPP_INCLUDED__'是一個保留名稱 - 不要使用雙下劃線。 – Barry
通過類實例調用靜態函數有點奇怪(允許,但很奇怪)。你真的打算這些功能是靜態的嗎? – GManNickG
不相關,但你可以從C++ 11開始使用'std :: thread'。 'pthread'現在只是看起來糟糕! :) – Arunmu