c++ - ld: 2 duplicate symbols for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) -
either pebkac or mac dumb. have following code.
main.cpp
#include <iostream> #include "parser.h" using namespace std; const char *filename = "main.c"; int main() { cout<<"parser"<<endl; parser *p = new parser(filename); p->parse(); return 0; }
parser.h
#ifndef parser_h #define parser_h struct parser { parser(const char* filename_); bool parse(); private: const char* filename; }; parser::parser(const char* filename_):filename(filename_){} #endif
parser.cpp
#include "parser.h" #include <iostream> bool parser::parse() { std::cout<<"the file name "<<filename<<std::endl; return false; }
i following error when try compile using command
g++ parser.cpp main.cpp
duplicate symbol __zn6parserc2epkc in: /var/folders/sh/3w74dm6n05jbtbv6hzx9f3_00000gn/t/parser-7ddc8e.o /var/folders/sh/3w74dm6n05jbtbv6hzx9f3_00000gn/t/main-90a53f.o duplicate symbol __zn6parserc1epkc in: /var/folders/sh/3w74dm6n05jbtbv6hzx9f3_00000gn/t/parser-7ddc8e.o /var/folders/sh/3w74dm6n05jbtbv6hzx9f3_00000gn/t/main-90a53f.o ld: 2 duplicate symbols architecture x86_64 clang: error: linker command failed exit code 1 (use -v see invocation)
when remove ' "#include "parser.h" ' parser.cpp, error disappears (if cannot define functions in parser.cpp file). isnt guarding whole point of avoiding duplicate symbols? not sure why wont work in mac? (i using mac console btw). tried many threads, no answer clear. sorry if duplicate
mac: 1 me:0
found out answer, not sure why defining constructor outside class in parser.h file. either should have defined inside class or outside in .cpp file. article helped me understand doing wrong.
http://samwho.co.uk/blog/2013/12/08/duplicate-symbol-what/
parser.h
struct parser { parser(const char* filename_); bool parse();
private: const char* filename; }; parser::parser(const char* filename_):filename(filename_){} <-- problem, has either defined inside class or outside in .cpp.
this fixed it. (should write code in c++ more often). guess wont delete thread, have feeling need it. couldn't find many resources g++. (not many people using g++ in mac suppose)
parser.h
struct parser { parser(const char* filename_): filename(filename_){} bool parse(); private: const char* filename; };
Comments
Post a Comment