我有我的main.cpp:
#include <boost/thread.hpp>
#include "../headers/BoostUDPSender.h"
#include "../headers/UDPListener.h"
#include "../headers/UDPPacket.h"
using namespace std;
int main(int argc, char** argv) {
cout << argv[1] << endl;
cout << argv[2] << endl;
BoostUDPSender boostUDPSend;
boostUDPSend.boostUDPPacket(argv[1], argv[2]);
}
和我的BoostUDPSender.h
#ifndef BOOSTUDPSENDER_H_
#define BOOSTUDPSENDER_H_
class BoostUDPSender {
public:
BoostUDPSender();
int boostUDPPacket(char* ipStr, char* port);
};
#endif /* BOOSTUDPSENDER_H_ */
和BoostUDPSender.cpp
#include "../headers/BoostUDPSender.h"
#include <string>
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <arpa/inet.h>
using boost::asio::ip::udp;
using namespace boost::asio::ip;
BoostUDPSender::BoostUDPSender() {
}
int boostUDPPacket(char* ipStr, char* port){
try
{
boost::asio::io_service io_service;
udp::resolver resolver(io_service);
udp::resolver::query query(udp::v4(), ipStr, port);
udp::endpoint receiver_endpoint = *resolver.resolve(query);
udp::socket socket(io_service);
socket.open(udp::v4());
boost::array<char, 1> send_buf = {{ 0 }};
socket.send_to(boost::asio::buffer(send_buf), receiver_endpoint);
boost::array<char, 128> recv_buf;
udp::endpoint sender_endpoint;
size_t len = socket.receive_from(
boost::asio::buffer(recv_buf), sender_endpoint);
std::cout.write(recv_buf.data(), len);
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
这一切对我来说都很好,但是当我编译时(下面包含的其他文件,与上面的内容无关):
g++ UDPListener.cpp UDPPacket.cpp BoostUDPSender.cpp main.cpp -o main -lboost_thread -lboost_system -lpthread -std=c++11
我明白了:
/tmp/ccFPtASO.o: In function `main':
main.cpp:(.text+0x8f): undefined reference to `BoostUDPSender::boostUDPPacket(char*, char*)'
collect2: error: ld returned 1 exit status
我不明白boostUDPPacket()
是如何定义的,我是以传统的方式创建我的对象并在其上调用方法?
答案 0 :(得分:1)
您不是将该函数定义为成员函数,而是将其定义为免费(非成员)函数。
从
更改定义int boostUDPPacket(char* ipStr, char* port){
到
int BoostUDPSender::boostUDPPacket(char* ipStr, char* port){
// ~~~~~~~~~~~~~~~~