I am a beginner in C++. I have my header files and source files stored in different folders as shown below. When I try to compile, I am unable to compile successfully.
test
├── inc
│ └── A.h
├── src
│ └── A.cpp
└── test.cpp
test.cpp
#include <iostream>
#include "inc\A.h"
int main() {
std::cout << A();
return 0;
}
A.h
#ifndef A_H
#define A_H
int A();
#endif
A.cpp
#include "..\inc\A.h"
int A() {
return 1;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
project(CPPproject)
SET(MAIN test.cpp)
SET(CMAKE_CXX_STANDARD 17)
SET(Home "D:\study\test")
SET(EXECUTABLE_OUTPUT_PATH ${Home})
include_directories("${PROJECT_SOURCE_DIR}/inc")
file(GLOB MAIN_SRC "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")
file(GLOB MAIN_HEAD "${CMAKE_CURRENT_SOURCE_DIR}/inc/*.h")
add_executable(test ${MAIN})
errors:
[build] CMakeFilestest.dir/objects.a(test.cpp.obj): In function `main':
[build] D:/study/test/test.cpp:4: undefined reference to `A()'
[build] collect2.exe: error: ld returned 1 exit status
I made some changes and replaced #include "inc\A.h"
in the main file with #include "src\A.cpp"
, and the compilation was successful. However, I don’t understand the reason behind it. This approach doesn’t seem normal.
New contributor
Akarin akaza is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1