Halbort Halbort - 1 month ago 11
C++ Question

Redefinition of custom delete

I am getting an error saying that I have redefined a function custom_delete.

header.h

#include <iostream>
#include <string>

static int unfreed_count = 0;
#define DELETE(O) custom_delete(O,__PRETTY_FUNCTION__, __LINE__)

void custom_delete(void* ptr, const std::string& function_name, unsigned int line_number) {
unfreed_count--;
std::cout << "delete called in " + function_name + ":" << line_number << std::endl;
std::cout << "unfreed_count: = " << unfreed_count << std::endl << std::endl;
free(ptr);
}


main.cpp

#include "header.h"

int main(int argc, char* argv[]) {
int* ptr = new int;
DELETE(ptr);
}


This code results in the following error message upon attempted compilation:

main.cpp: In function 'void custom_delete(void*, const string&, unsigned int)':
main.cpp:5:6: error: redefinition of 'void custom_delete(void*, const string&, unsigned int)'
void custom_delete(void* ptr, const std::string& function_name, unsigned int line_number) {
^
In file included from main.cpp:21:0:
header.h:7:6: note: 'void custom_delete(void*, const string&, unsigned int)' previously defined here
void custom_delete(void* ptr, const std::string& function_name, unsigned int line_number) {
^


I was trying to make a custom version of delete that printed out when it was used. This was in a larger project, so I made a separate project with just these two files and got the same errors.

I tried commenting out all the code inside the
custom_delete
function. I also tried writing the prototype before the macro. I got the same error each time.

---EDIT---
I found there was another file being compiled:
header.cpp

#include "header.h"

// Some commented out functions


If I remove the
#include "header.h"
everything works. However, I eventually will need to add the functions to header.cpp. These functions need stuff that will be added to header.h. What should I do?

Answer

It looks like you don't have include guard in your headers.

Add #pragma once as the first line of your header.h

or for more portable solution, add

#ifndef HEADER_H
#define HEADER_H

as first two lines, and

#endif

as last line of the header.h.

Also, to avoid link errors, add inline keyword to declaration of your function, like inline void custom_delete(...

or move function implementation to .cpp.

Comments