I have two files, Snake.h and Snake.cpp.
In Snake.h:
std::array<int, GAME_WIDTH* GAME_HEIGHT + 1> getSnake() const;
int getSize() const;
int getApple() const;
In Snake.cpp:
std::array<int, GAME_WIDTH* GAME_HEIGHT + 1> Snake::getSnake() const {
return snake;
}
int Snake::getSize() const {
return size;
}
int Snake::getApple() const {
return apple;
}
When I try to make these inline functions, I get a LNK2019 error, but if I leave it as is it compiles and runs perfectly fine. Any ideas why this would be?
The LNK2019 error usually indicates unresolved external symbols. When you make a function inline
, the definition should be available at the point of instantiation. If the function definition is in a .cpp
file, other translation units won't see the definition, causing the linker error.
Solutions:
inline
keyword in both declaration and definition, and include the header where needed.Example for Solution 1:
// In Snake.h
inline std::array<int, GAME_WIDTH* GAME_HEIGHT + 1> getSnake() const {
return snake;
}
Now the inline function definition is in the header, making it visible to all translation units that include the header. This should resolve the LNK2019 error.
Do the same for the other int
functions if you want to make them inline.