When building a header-only library it is very likely that we include the implementation header at the end of the main header as well as the main header at the beginning of the implementation header.
The reason is very simple, the user shall only include the main header, hence the main header is responsible for including its implementation. On the other hand, while developing the header-only library, it’s necessary to include the main header file at the beginning in order to benefit from Clangd features.
However, if this approach is used, Clangd will report an error stating we cannot include the main file recursively when building a preamble.
{ "resource": "/home/user/Library/include/impl/feature_a.hpp", "owner": "_generated_diagnostic_collection_name_#0", "code": "pp_including_mainfile_in_preamble", "severity": 8, "message": "In included file: main file cannot be included recursively when building a preamble", "source": "clang", "startLineNumber": 1, "startColumn": 10, "endLineNumber": 1, "endColumn": 47, "relatedInformation": [ { "startLineNumber": 328, "startColumn": 10, "endLineNumber": 328, "endColumn": 52, "message": "Error occurred here", "resource": "/home/user/Library/include/feature_a.hpp" } ] }
For example:
Header definition
// include/feature_a.hpp #ifndef MY_HEADER_ONLY_LIBRARY_FEATURE_A_HPP #define MY_HEADER_ONLY_LIBRARY_FEATURE_A_HPP ... // header definition ... // include the implementation file #include "impl/feature_a.hpp" #endif
Header implementation
// include/impl/feature_a.hpp // No need for header-guards // Include the main header definition - so we can implement using clangd features. // Note - this is not a requirement for compilation since this is being included in the header file. #include "feature_a.hpp" ... // header implementation ...
What I expected
Since the main header file has header-guards, clangd should check that, even though the file is being recursively included, the header-guards will stop the recursion safely.
System information
Output of clangd --version
: clangd version 9.0.0-2~ubuntu18.04.2 (tags/RELEASE_900/final)
Editor/LSP plugin: VSCode with ClangD extension.
Operating system: Ubuntu 18.04
Forum Updated on Feb 6th
This topic has been deleted. Only users with topic management privileges can see it.
-
I am getting below error in qt creator.
Error — in included file: main file cannot be included recursively when building a preamble
Please provide solution on this error
-
@Abhijeet-Gurav said in General include file error:
Please provide solution on this error
Please provide more information.
What are you including where? It looks like you have reqursive includes. -
In 1 user defined include file I am including another user defined include file with one more user defined include file. Total 3 user defined include files.
and in that one more user defined include file I need another user defined include file so I am including that.
This is little bit confusing but in this case I am getting error. -
@Abhijeet-Gurav
Well the «solution» is to untangle your#include
s so that you don’t need a circular include. You probably should not need to. Otherwise check the#ifndef
guard statements at the head of each included file which Qt would put in for you if you let it create the files from classes or you may have put in yourself.
Differential D53866
Authored by nik on Oct 30 2018, 7:12 AM.
- Edit Revision
- Update Diff
- Download Raw Diff
- Mute Notifications
- Award Token
- Flag For Later
- Restricted Project
arphaman |
cfe-commits |
jan-wassenberg |
jdoerfert |
yvvan |
- Reviewers
-
erikjv ilya-biryukov
- Repository
- rC Clang
- Build Status
-
Buildable 31737 Build 31736: arc lint + arc unit
Event Timeline
nik created this revision.
Herald added subscribers: cfe-commits, arphaman.
Harbormaster completed remote builds in B24325: Diff 171689.
nik added reviewers: erikjv, ilya-biryukov.
nik added a subscriber: yvvan.
Comment Actions
Comment Actions
Comment Actions
Comment Actions
Comment Actions
Comment Actions
Comment Actions
Comment Actions
Comment Actions
Harbormaster completed remote builds in B25314: Diff 175210.
Comment Actions
ilya-biryukov added inline comments.
include/clang/Lex/Preprocessor.h | ||
---|---|---|
391 ↗ | (On Diff #175210) | |
lib/Lex/PPDirectives.cpp | ||
1883 |
nik marked 2 inline comments as done.
nik added inline comments.
include/clang/Lex/Preprocessor.h | ||
---|---|---|
391 ↗ | (On Diff #175210) | |
lib/Lex/PPDirectives.cpp | ||
1883 |
Comment Actions
Harbormaster completed remote builds in B25731: Diff 176826.
nik retitled this revision from [Preamble] Fix preamble for circular #includes to [Preamble] Stop generating preamble for circular #includes.
nik edited the summary of this revision. (Show Details)
ilya-biryukov added inline comments.
include/clang/Lex/Preprocessor.h | ||
---|---|---|
391 ↗ | (On Diff #175210) | |
lib/Lex/PPDirectives.cpp | ||
1883 | ||
1884 |
nik marked 2 inline comments as done and an inline comment as not done.
nik added inline comments.
include/clang/Lex/Preprocessor.h | ||
---|---|---|
391 ↗ | (On Diff #175210) |
Comment Actions
Harbormaster completed remote builds in B25758: Diff 176941.
ilya-biryukov added inline comments.
include/clang/Basic/DiagnosticLexKinds.td | ||
---|---|---|
430 | ||
include/clang/Lex/Preprocessor.h | ||
391 ↗ | (On Diff #175210) |
nik marked 2 inline comments as done.
nik added inline comments.
include/clang/Lex/Preprocessor.h | ||
---|---|---|
391 ↗ | (On Diff #175210) |
Herald added a project: Restricted Project.
Herald added a subscriber: jdoerfert.
Comment Actions
Harbormaster completed remote builds in B28137: Diff 186813.
nik marked an inline comment as done.
nik added inline comments.
lib/Basic/SourceManager.cpp | |
---|---|
1594 |
nik retitled this revision from [Preamble] Stop generating preamble for circular #includes to [Preamble] Stop circular inclusion of main file when building preamble.
nik edited the summary of this revision. (Show Details)
Comment Actions
Comment Actions
Comment Actions
Comment Actions
Harbormaster completed remote builds in B31610: Diff 198654.
Comment Actions
lib/Basic/SourceManager.cpp | |
---|---|
1594 |
nik marked an inline comment as done.
nik added inline comments.
lib/Basic/SourceManager.cpp | |
---|---|
1594 |
Comment Actions
Harbormaster completed remote builds in B31666: Diff 198799.
ilya-biryukov added inline comments.
lib/Basic/SourceManager.cpp | |
---|---|
1594 |
nik marked an inline comment as done.
nik added inline comments.
lib/Basic/SourceManager.cpp | |
---|---|
1594 |
Comment Actions
include/clang/Basic/DiagnosticLexKinds.td | |
---|---|
429 | |
lib/Basic/SourceManager.cpp | |
1594 |
This revision is now accepted and ready to land.
Comment Actions
Harbormaster completed remote builds in B31737: Diff 198997.
Comment Actions
Comment Actions
Comment Actions
- Files
- History
- Commits
Path | Size | ||||
---|---|---|---|---|---|
|
|||||
|
2 lines | ||||
|
|||||
|
|||||
|
2 lines | ||||
|
|||||
|
12 lines | ||||
|
|||||
|
9 lines |
View Options
Loading…
View Options
Loading…
View Options
Loading…
View Options
Loading…
Log In to Comment
For example:
I have a class called A. And there is:
A.hpp
A.cpp
main.cpp
for my project
By default, I only need to include A.hpp in the main so I can compile it, either using IDE such as Xcode or using:
g++ main.cpp A.cpp -o xxxxx
But the submission system only allows me to use:
g++ main.cpp -o xxxx
I tried to include A.cpp in the main, but the IDE says: main file cannot be included recursively when building a preamble
Is there any solution? I want to keep my hpp and cpp separately.
asked Sep 15, 2020 at 13:37
12
Can I include a cpp file
In theory, any file can be included.
But as a convention, you should never include cpp files.
But the submission system only allows me to use:
g++ main.cpp -o xxxx
If you cannot compile A.cpp then don’t write such file at all. Write the definitions that you would have written in A.cpp into main.cpp instead. This achieves the same as including with a macro, but there won’t be duplicate definitions in another cpp file.
answered Sep 15, 2020 at 14:21
eerorikaeerorika
229k12 gold badges193 silver badges318 bronze badges
You can #include
any file you want. #include
is automatic copy-paste. It looks in the file you tell it to include, and it reads whatever’s in the file, and it pretends you wrote that in your original file. It doesn’t care what’s in the file, it just does that. You can include a .h
file, a .hpp
file, a .cpp
file, a .txt
file, a .py
file, a .jpg
file, or anything you want, as long as it’s got valid C++ code in it.
Note that including a .cpp
file is not the same as compiling it separately. And people expect that .cpp
files are compiled separately, not included. To avoid confusing other programmers or the future version of yourself, you should rename the file to something else if you want to include it. You don’t have to, but you should. If it’s not a normal header file either (because you can’t include it more than once), then you can make up some completely different extension, like .inc
.
answered Sep 15, 2020 at 14:21
user253751user253751
55.4k6 gold badges45 silver badges88 bronze badges
2019-11-25 12:35:13,620 - INFO - Received ready request
2019-11-25 12:35:13,623 - INFO - Received signature help available request
2019-11-25 12:35:13,624 - INFO - Received event notification
2019-11-25 12:35:13,626 - INFO - Received event notification
2019-11-25 12:35:13,626 - INFO - Adding buffer identifiers for file: /Users/maxcoplan/test.c
2019-11-25 12:35:13,635 - ERROR - No Clangd executable found at /usr/local/Cellar/llvm/9.0.0/bin/clangd
2019-11-25 12:35:13,635 - ERROR - Semantic completion not available for ['c']
Traceback (most recent call last):
File "/Users/maxcoplan/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/server_state.py", line 114, in FiletypeCompletionAvailable
self.GetFiletypeCompleter( filetypes )
File "/Users/maxcoplan/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/server_state.py", line 100, in GetFiletypeCompleter
current_filetypes ) )
ValueError: No semantic completer exists for filetypes: ['c']
2019-11-25 12:35:13,636 - ERROR - Semantic completion not available for ['c']
Traceback (most recent call last):
File "/Users/maxcoplan/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/server_state.py", line 114, in FiletypeCompletionAvailable
self.GetFiletypeCompleter( filetypes )
File "/Users/maxcoplan/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/server_state.py", line 100, in GetFiletypeCompleter
current_filetypes ) )
ValueError: No semantic completer exists for filetypes: ['c']
2019-11-25 12:35:13,725 - INFO - Received filetype completion available request
2019-11-25 12:35:13,725 - ERROR - Semantic completion not available for ['c']
Traceback (most recent call last):
File "/Users/maxcoplan/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/server_state.py", line 114, in FiletypeCompletionAvailable
self.GetFiletypeCompleter( filetypes )
File "/Users/maxcoplan/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/server_state.py", line 100, in GetFiletypeCompleter
current_filetypes ) )
ValueError: No semantic completer exists for filetypes: ['c']
2019-11-25 12:35:13,780 - INFO - Received event notification
2019-11-25 12:35:13,781 - INFO - Adding ONE buffer identifier for file: /Users/maxcoplan/test.c
2019-11-25 12:35:13,781 - ERROR - Semantic completion not available for ['c']
Traceback (most recent call last):
File "/Users/maxcoplan/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/server_state.py", line 114, in FiletypeCompletionAvailable
self.GetFiletypeCompleter( filetypes )
File "/Users/maxcoplan/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/server_state.py", line 100, in GetFiletypeCompleter
current_filetypes ) )
ValueError: No semantic completer exists for filetypes: ['c']
2019-11-25 12:35:14,387 - INFO - Received event notification
2019-11-25 12:35:14,387 - INFO - Adding buffer identifiers for file: /Users/maxcoplan/test.c
2019-11-25 12:35:14,387 - ERROR - Semantic completion not available for ['c']
Traceback (most recent call last):
File "/Users/maxcoplan/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/server_state.py", line 114, in FiletypeCompletionAvailable
self.GetFiletypeCompleter( filetypes )
File "/Users/maxcoplan/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/server_state.py", line 100, in GetFiletypeCompleter
current_filetypes ) )
ValueError: No semantic completer exists for filetypes: ['c']
2019-11-25 12:35:14,388 - INFO - Received event notification
2019-11-25 12:35:14,388 - ERROR - Semantic completion not available for ['c']
Traceback (most recent call last):
File "/Users/maxcoplan/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/server_state.py", line 114, in FiletypeCompletionAvailable
self.GetFiletypeCompleter( filetypes )
File "/Users/maxcoplan/.vim/bundle/YouCompleteMe/third_party/ycmd/ycmd/server_state.py", line 100, in GetFiletypeCompleter
current_filetypes ) )
ValueError: No semantic completer exists for filetypes: ['c']
2019-11-25 12:35:18,445 - INFO - Received completion request
2019-11-25 12:35:18,445 - ERROR - Semantic completion not available for ['c']
Traceback (most recent call last):
Fi
I have installed clangd with :LspInstallServer
but the diagnostic throws errors when I include any standard library files.
#include <string>
results in:
main.cpp|1 col 10| clang:Error:pp_file_not_found:In included file: 'string.h' file not found /Users/maciej/.vim/bundle/vim-lsp-settings/servers/clangd/bin/../include/c++/v1/string.h:60:15: note: error occurred here
I took a look at the string
in the .vim/bundle/vim-lsp-settings/servers/clangd/bin/../include/c++/v1/
and it fails at:
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif
#include_next <string.h>
with the diagnostics:
string.h|57 col 13| clang:Warning:-Wpragma-system-header-outside-header:#pragma system_header ignored in main file
string.h|57 col 13| clang:Warning:-Wpragma-system-header-outside-header:#pragma system_header ignored in main file
string.h|60 col 15| clang:Error:pp_including_mainfile_in_preamble:Main file cannot be included recursively when building a preamble
I am not sure whether it is my fault, something wrong with the vim-lip-settings or with the llvm code that is downloaded with the :LspInstallServer
, but the c++ diagnostics doesn’t work out of the box.
Also it results in very superficial autocompletion of stl, because the clangd can’t parse the library and does not complete methods/members of classes.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
12 / 12 / 0 Регистрация: 31.08.2011 Сообщений: 458 |
|
1 |
|
14.07.2014, 06:31. Показов 5707. Ответов 11
Ошибка выскакивает в файле fig11_08.cpp на 8 строке. Уже второй раз сталкиваюсь с этим и понял, что так дело больше не пойдет, надо разобраться. Помогите понять, что он хочет.
__________________
0 |
12 / 12 / 0 Регистрация: 31.08.2011 Сообщений: 458 |
|
14.07.2014, 07:22 [ТС] |
2 |
в файлах кое где остались синтакс ошибки. Это может быть причиной? Верней не синтакс, а орфографические, не знаю как их назвать в среде программирования. То есть кавычки где то не стоят, или вместо буквы цифра. Так из пдф копирование происходит через буфер.
0 |
uglyPinokkio 327 / 230 / 55 Регистрация: 30.05.2014 Сообщений: 682 |
||||||||||||
14.07.2014, 08:08 |
3 |
|||||||||||
в файлах кое где остались синтакс ошибки. Это может быть причиной? Может Добавлено через 37 минут Кликните здесь для просмотра всего текста
1 |
12 / 12 / 0 Регистрация: 31.08.2011 Сообщений: 458 |
|
17.07.2014, 23:46 [ТС] |
4 |
ты крут, мега мозг ). Я то сверяю каждую строчку с книгой и то пропустил где-то, а ты просто сверял со своей логикой и получилось. Добавлено через 40 минут
Синтаксис поправил Как ты это сделал, открой секрет. Сейчас другой проект скопировал, опять та же ошибка. Не поленился прошел каждую строчку отдельно, сверил, все равно ошибка выскакивает. Может какая метода есть у тебя?
0 |
327 / 230 / 55 Регистрация: 30.05.2014 Сообщений: 682 |
|
18.07.2014, 06:10 |
5 |
Может какая метода есть у тебя? Нет, просто я этим на жизнь зарабатываю .
0 |
Тимур05 12 / 12 / 0 Регистрация: 31.08.2011 Сообщений: 458 |
||||||||||||
18.07.2014, 14:04 [ТС] |
6 |
|||||||||||
Есть еще один не большой проект, хочу показать тебе, может поможешь, просто указать где ошибки, чтоб самому понять, что я пропустил. Здесь я сам каждую строчку проверил по книге, строка в строку, но все равно выскакивает ошибка (название темы). В комментариях если есть ошибки, то их я игнорирую, так как компилятор то же не смотрит на них.
0 |
5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
|
18.07.2014, 15:30 |
7 |
Ошибки какие-то странные: в нескольких местах, вместо английской o русская (ostream), вместо ноля — буква О (if ( string2 != 0 )). Откуда взяли метод void String::setstring( const char *string2 ) (в String.срр)? В классе такого нет, есть setString.
0 |
327 / 230 / 55 Регистрация: 30.05.2014 Сообщений: 682 |
|
18.07.2014, 17:50 |
8 |
Ошибки какие-то странные Да копипаста из pdf как пить дать. В выходные поправлю, если время будет.
0 |
5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
|
18.07.2014, 19:09 |
9 |
Да я, в общем-то, поправил.
1 |
12 / 12 / 0 Регистрация: 31.08.2011 Сообщений: 458 |
|
18.07.2014, 23:57 [ТС] |
10 |
Да копипаста из pdf как пить дать. да, оно самое из оттуда самого ). Я с книги примеры копирую себе в компилятор и ,изучая С++, параллельно смотрю на живом выполнении программы. Но вот копипаста из пдф не все символы правильно распознает. Вместо s1 может написать si.
вместо английской o русская (ostream) а как ты это увидел? Я даже и не думал, что копирование так будет происходить.
Откуда взяли метод void String::setstring( const char *string2 ) (в String.срр)? да, это ошибка. Там с большой буквы надо, как ты написал. Добавлено через 3 минуты
Да я, в общем-то, поправил. а как ты поправил? Я например, вижу один вариант как это можно сделать. В одном окне открыть оригинал а во втором заново напечатать самому, глядя на первый. Тогда все символы точно будут в нужном языке.
0 |
5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
|
19.07.2014, 00:24 |
11 |
а как ты это увидел? Догадался (с подсказкой компилятора).
а как ты поправил? Заменил букву.
0 |
327 / 230 / 55 Регистрация: 30.05.2014 Сообщений: 682 |
|
19.07.2014, 05:33 |
12 |
да, оно самое из оттуда самого ). Я с книги примеры копирую себе в компилятор и ,изучая С++, параллельно смотрю на живом выполнении программы. Но вот копипаста из пдф не все символы правильно распознает. Вместо s1 может написать si. Не копируй,набирай руками.
0 |