C++ 将helper函数移动到头文件

C++ 将helper函数移动到头文件,c++,c++14,header-files,C++,C++14,Header Files,一开始我有: main.cpp #include "something.h" #include "util.h" int main() { sth::something(); utl::little_thing(); } 某物 #ifndef SOMETHING_H #define SOMETHING_H namespace sth { void something(); } #endif somehing.cpp #include "something.h" #i

一开始我有:

main.cpp

#include "something.h"
#include "util.h"

int main() {
    sth::something();
    utl::little_thing();
}
某物

#ifndef SOMETHING_H
#define SOMETHING_H

namespace sth {

void something();

}
#endif
somehing.cpp

#include "something.h"

#include <string>
#include <iostream>

namespace sth {

void print_me(std::string txt) {
    std::cout << txt << std::endl;
}

void something() {
    std::cout << "this is something" << std::endl;
    print_me("optional");
}
}
util.cpp

#include "util.h"

#include <iostream>
#include <string>

namespace utl {

void little_thing() {
    std::cout << "this is little thing" << std::endl;
}
}
某物

#include "something.h"
#include "util.h"

#include <string>
#include <iostream>

namespace sth {

void something() {
    std::cout << "this is something" << std::endl;
    utl::print_me("optional");
}
}
这对我来说很有意义,因为
util.h
包含在
main.cpp
something.cpp
中有重复的符号,对吗


问题,是否有可能懒得把所有的东西都放在标题中?或者没有办法,必须拆分贴花和定义?我不想(在本例中)将实现隐藏在.cpp中,我只想将其移出
sth
也许可以将
print\u me
的定义下放到
util.cpp
中,并且只在
util.h
文件中保留它的声明


<> P>否则,在每个对象文件中都会得到它的副本,然后链接器会因为它们都有相同的名称(符号)而变得混淆。<>代码>静态内联是您的朋友:)@ HealLe>代码>内联< /代码>的副本可能在UTIL中的C++中见PrimtTyMe()定义。头文件中的定义可能会导致重复的符号警告。该死,你说得对。我读了很多C代码,您(被迫)使用
静态内联
:)
#ifndef UTIL_H
#define UTIL_H

#include <string>
#include <iostream>

namespace utl {

void little_thing();

void print_me(std::string txt) {
    std::cout << txt << std::endl;
}
}
#endif
#include "something.h"
#include "util.h"

#include <string>
#include <iostream>

namespace sth {

void something() {
    std::cout << "this is something" << std::endl;
    utl::print_me("optional");
}
}
c++ -std=gnu++14 -g -Wall -O3  -c -o main.o main.cpp
c++ -std=gnu++14 -g -Wall -O3  -c -o util.o util.cpp
c++ -std=gnu++14 -g -Wall -O3  -c -o something.o something.cpp
c++ main.o util.o something.o  -o main
duplicate symbol __ZN3utl8print_meENSt3__112basic_stringIcNS0_11char_traitsIcEENS0_9allocatorIcEEEE in:
    main.o
    util.o
duplicate symbol __ZN3utl8print_meENSt3__112basic_stringIcNS0_11char_traitsIcEENS0_9allocatorIcEEEE in:
    main.o
    something.o
ld: 2 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [main] Error 1