Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

visual c++ - C++ #define value not defined in source file

I'm defining a value in my Main-file and then including a header file. The defined value isn't defined in the source file.

Main.cpp:

#define TN_VALUE double
#include "SomeFile.hpp"

int main()
{
  TN_VALUE x = 3;
  func(x);
  return 0;
}

SomeFile.hpp:

#ifndef _SOME_FILE
#define _SOME_FILE
#ifndef TN_VALUE
#define TN_VALUE float
#endif
void func(TN_VALUE); // TN_VALUE = double
#endif

SomeFile.cpp:

#include "SomeFile.hpp"
#include <iostream>

void func(TN_VALUE _value) // TN_VALUE = float
{
  std::cout << _value << std::endl;
}
question from:https://stackoverflow.com/questions/65644359/c-define-value-not-defined-in-source-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm assuming your question is,
Why does TN_VALUE is double in Main.cpp and float in SomeFile.cpp.

For that question, this is the explanation,
In C++, when you include a header file, it's content gets copied to the source file. Which means that there will be one copy of the SomeFile.hpp file in Main.cpp file and another copy in the SomeFile.cpp file. So now when the compiler runs through the source file, in one file the definition of TN_VALUE is float (in SomeFile.cpp) and its value is double (because you have defined it explicitly) in the other file (Main.cpp).
This means that there will be two different (overloaded) functions. One is void func(float) and the other is void func(double).

Since the function definition is present in the SomeFile.cpp file, it'll compile without an issue, but the Main.cpp file will have an issue because the compiler says that there's a function with the signature of void func(double) which the linker cannot find (because a function like that is not compiled). This will trigger a link error.

To resolve this issue, you can define the function in the header file itself and ditch the SomeFile.cpp file altogether. This way the function definition will be placed in the Main.cpp file and the definition of the TN_VALUE will resolve to double. No linking errors will arise from this function after that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...