首页 文章

将辅助函数移动到头文件

提问于
浏览
0

一开始我有:

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

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.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;
}
}

然后我尽管从 sth 名称空间中获得 print_me(std::string txt) 会更好 . 我把它放在 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.cppsomething.cpp 中有重复的符号,对吗?

问题,是否有可能在 Headers 中保持一切懒惰?或者没有办法,必须分割decalration和定义?我不关心(在这种情况下)隐藏.cpp中的实现,我只是想将它移出 sth .

1 回答

  • -1

    也许将 print_me 的定义下移到 util.cpp 并且只在 util.h 文件中留下它的声明 .

    否则,你会在每个目标文件中获得它的副本,然后链接器会因为它们都具有相同的名称(符号)而感到困惑 .

相关问题