# How to correctly align caption with code listing

I am using the listing package to display my source code as follows:

\lstset{language=C++,basicstyle=\footnotesize\ttfamily,emptylines=1,breaklines=true,backgroundcolor=\color{light-gray},xleftmargin=-1.cm,frame=lr,framesep=8pt,framerule=0pt}
\lstset{numbers=left,tabsize=2}


By using xleftmargin=-1.cm, I am able to slightly push the code listing to the left into the margin. The resulting layout is shown below:

As you can see the caption is not correctly aligned with the code listing. I would like to push the listing's caption to the left in a similar way so that both code listing and captions are aligned and cover the same page length.

Edit As requested, here is the MWE:

\documentclass[10pt,twoside]{book}
\usepackage{listings}
\usepackage{color} \usepackage[font=small,format=plain,labelfont=bf,sl,textfont=normal,justification=justified,singlelinecheck=false]{caption}
\usepackage{lipsum}

\begin{document}

\definecolor{javared}{rgb}{0.6,0,0} % for strings
\definecolor{javapurple}{rgb}{0.5,0,0.35} % keywords

\lstset{
keywordstyle=\color{javapurple}\bfseries,
stringstyle=\color{javared},

\definecolor{light-gray}{gray}{0.95}
\lstset{language=C++,basicstyle=\footnotesize\ttfamily,emptylines=1,breaklines=true,backgroundcolor=\color{light-gray},xleftmargin=-1.cm,frame=lr,framesep=8pt,framerule=0pt}
\lstset{numbers=left,tabsize=2}

\lipsum[1]
\begin{lstlisting}[caption=random02.cpp]
#include <iostream>
#include <random>
#include <time.h>
int main(){
time_t seed = time(nullptr);
std::mt19937 randomEngine(seed);
std::uniform_int_distribution<int> dist(1,6);
for(int i=0; i < 10; i++){
std::cout << dist(randomEngine) << std::endl;
}
}
\end{lstlisting}
\lipsum[2]

\end{document}


Edit 2: Only code listings should be impacted by this formatting. Other captions should be displayed with their default style defined in the document

• Please post a compilable code starting with \begin{document} and ending with \end{document}, not just code snippets. – Troy Mar 5 '17 at 2:03
• Can you please make your code compilable? Including a documentclass and the necessary packages? – user36296 Mar 5 '17 at 12:36
• Sorry about that. Edited the MWE to be compilable and made sure to test before submitting. – BigONotation Mar 5 '17 at 12:56