C++助手函数存放位置咨询:应放.cpp还是.h文件以支持#include?
Great question! Let's break this down based on C++ best practices:
First, let's look at your code:
namespace test { void doSomething() { // Do stuff } }
This is a full function definition (it includes the actual function body with your implementation code).
Here's the key guidance:
Put this full definition in a
.cppfile (liketest.cpp). If you place a function with a body into a.hfile, every other.cppfile that#includes that header will generate a duplicate copy of the function definition. When the linker tries to combine all compiled object files, it'll throw a multiple definition error—it can't resolve which copy of the function to use!If you want other files to call
doSomething(), create a matching.hfile (liketest.h) and put only the function declaration there (no body):namespace test { void doSomething(); // Just the function signature, no curly braces or code }Then, make sure your
.cppfile includes this.hfile—this lets the compiler verify that the declaration and definition match perfectly.Don't forget to add header guards to your
.hfile to prevent accidental repeated includes. You can use the classic#ifndefpattern:#ifndef TEST_H #define TEST_H // Your function declaration here #endif // TEST_HOr the simpler
#pragma once(supported by most modern compilers) at the very top of the.hfile.
With this setup, you can safely #include "test.h" in any other .cpp file that needs to use test::doSomething(), and the linker will find the single, valid definition in test.cpp without conflicts.
Hope that clears things up for you!
内容的提问来源于stack exchange,提问作者user14271364

