正在将助手函数移动到头文件
Moving helper function to header file
一开始我有:
main.cpp
#include "something.h"
#include "util.h"
int main() {
sth::something();
utl::little_thing();
}
somehing.h
#ifndef SOMETHING_H
#define SOMETHING_H
namespace sth {
void something();
}
#endif
某些.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.h
#ifndef UTIL_H
#define UTIL_H
namespace utl {
void little_thing();
}
#endif
util.cpp
#include "util.h"
#include <iostream>
#include <string>
namespace utl {
void little_thing() {
std::cout << "this is little thing" << std::endl;
}
}
那么我认为最好将print_me(std::string txt)
从sth
命名空间中移除。我把它放在utl
上,在.h文件上声明,在.cpp文件上定义。
在那一刻,我懒惰的一面说——像以前一样,把所有东西都放在一个文件里会更好吗。我试过了:
util.h
#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
something.cpp
#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
这对我来说很有意义,因为util.h
包含在main.cpp
和something.cpp
中,所以存在重复的符号,对吧?
问题,有没有可能懒洋洋地把所有的东西都放在标题里?或者没有办法,必须分开贴花和定义?我不在乎(在这种情况下(将实现隐藏在.cpp中,我只想将它从sth
中移出。
也许可以将print_me
的定义向下移动到util.cpp
,并只在util.h
文件中留下它的声明。
否则,在每个对象文件中都会得到它的副本,然后链接器会被混淆,因为它们都有相同的名称(符号(。
相关文章:
- 复制文件成功,移动文件失败,参数相同 - C++
- 错误:移动文件时'QString'为非标量类型"std::__cxx11::字符串"
- 快速从文件中读取下一个字符串,而无需移动文件的位置
- 如何使用C++在 Linux 中移动文件
- QT-如何移动文件
- 在巴泽尔移动文件
- C++:无法移动文件,因为文件夹名称上有空格
- 在C++中查找和移动文件
- 同时在Visual Studio和AnkhSVN中移动文件
- 使用SetFileInformationByHandle移动文件
- 在 matlab 中移动文件
- 在 Linux 中使用 C++ 跨卷移动文件
- 移动文件A()不喜欢我的参数
- C++ Windows 7上的移动文件错误(2)
- 为什么std::istream::read不根据读取的字节移动文件指针
- 是否可以使用FindFirstFile()来移动文件
- 读取文件:如何使用fscanf移动文件指针,以及scanf/fscanf如何处理丢失的%类型
- 移动文件() 不起作用
- 移动文件夹Windows c++:适用于Vista及以上版本,不包括XP
- 尝试使用带有C++的MoveFile移动文件时出现ERROR_INVALID_NAME