在尝试包含名为sniffer.h的文件时,Eclipse中出现“多重定义”错误。
sniffer.h:
#ifndef SNIFFER_H_
#define SNIFFER_H_
#include "sys/types.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "netdb.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <queue>
#include <pthread.h>
#include <sys/timeb.h>
#include <map>
#include <algorithm>
#include <math.h>
#include <syslog.h>
#include <signal.h>
#include <asm-generic/errno-base.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
//Syslog libraries.
#include <sys/wait.h>
#include <ctime>
using namespace std;
string gconfigfilename = "config"; //Holds the config file name, dynamic because of the add_interface option.
int pipehandler; //pipe handler for the pipe that the gulp writes to
string pipeFullName; //absolute path for the pipe that the gulp writes to
FILE* pipe_fd;
它包含sniffer.cpp中所有函数的语句:
#include "../h/sniffer.h"
void OpenPipeRead(/*string sinterface*/)
{
int ret_val;
pipeFullName = "";
pipeFullName.append(mconfig[C_PIPEPATH]);
//Its not empty only when there is argument for parallal telepath_sniff instances.
pipeFullName.append(mconfig[C_PIPENAME]);
//if(strcmp(sinterface.c_str(), "") != 0)
// lpipename.append("_" + sinterface);
printf("Try to open Pipe for reading\n");
syslog(LOG_INFO, "Try to open Pipe for reading\n");
/* Create the named - pipe */
ret_val = mkfifo(pipeFullName.c_str(), 0666);
if ((ret_val == -1) && (errno != EEXIST)) {
perror("Error creating the pipe");
syslog(LOG_ERR, "Error creating the pipe");
exit(1);
}
if((pipehandler = open(pipeFullName.c_str(), O_RDWR)) < 1) /* Open the pipe for reading and writing , in append mode */
{
perror("Failed to open pipe");
syslog(LOG_ERR, "Failed to open pipe");
exit(1);
}
printf("Pipe opened.\n");
syslog(LOG_INFO, "Pipe opened.\n");
}
然而,在第一个函数中,它表示pipeFullName
再次有多个定义。
我只包含一次,字符串在sniffer.h中定义。
答案 0 :(得分:5)
.cpp
文件!!! 这样做最终会违反 One definition Rule 。
通常的方法是在头文件中放置声明,在cpp文件中放置定义。
您可以根据需要多次声明某些内容,但只能定义一次。
所以你应该只包含头文件。如果包含cpp文件,则cpp文件中符号定义的副本会添加到包含头文件的每个翻译单元中,从而违反ODR。