std::string GetLocalComputerName() {
TCHAR chrComputerName[MAX_COMPUTERNAME_LENGTH + 1];
std::string strRetVal;
DWORD dwBufferSize = MAX_COMPUTERNAME_LENGTH + 1;
if(GetComputerName(chrComputerName,&dwBufferSize)) {
// We got the name, set the return value.
strRetVal = chrComputerName;
} else {
// Failed to get the name, call GetLastError here to get
// the error code.
strRetVal = "";
}
return(strRetVal);
}
I can call/use the function just fine. However, if I move it into a functions.cpp and include that in my file it starts throwing errors. I can't get it to work unless it's in teh main file. So how can I move my general functions into the other file to allow me to access it better?
#include "functions.hpp"
std::string GetLocalComputerName() {
TCHAR chrComputerName[MAX_COMPUTERNAME_LENGTH + 1];
std::string strRetVal;
DWORD dwBufferSize = MAX_COMPUTERNAME_LENGTH + 1;
if(GetComputerName(chrComputerName,&dwBufferSize)) {
// We got the name, set the return value.
strRetVal = chrComputerName;
} else {
// Failed to get the name, call GetLastError here to get
// the error code.
strRetVal = "";
}
return(strRetVal);
}
functions.hpp
1 2 3 4 5 6 7 8
#ifndef FUNCTIONS_HPP_
#define FUNCTIONS_HPP_ // header guard to make sure we only include the file once
#include <string>
std::string GetLocalComputerName();
#endif
main.cpp
1 2 3
#include "functions.hpp"
// do stuff with GetLocalComputerName
OK why do external C++ functions have to be in a .h file and not .cpp? I did hte same thing but in a .h file and it works fine......
I just have a functions.h with the function (plus the windows and string definition).....
So why did that work, but not the .cpp file?
I don't know how other compilers/IDE's work, but Visual Studio has the concept of projects.
A project can have (loosely speaking) header files or code files. Header files are of .h or .hpp extension, while code files can be .c, .cpp (maybe others). The compiler will compile code files ONLY. The header files are never compiled unless they are #included in a code file.
Sooo, you probably saw that the function was multiply defined when you moved it to function.cpp and #included this cpp file inside your other cpp file (I'll call it main.cpp). Why? Because the compiler compiled function.cpp into function.obj, and it also compiled your main.cpp file that also #included function.cpp, therefore duplicating the functions inside function.cpp.